Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自定义结构体转jsonStr的时候 打印出来的浮点值会有科学计数法的后缀E0 #255

Open
zyx199518 opened this issue Apr 19, 2024 · 7 comments

Comments

@zyx199518
Copy link

版本:v1.0.3

程序内部是:
double test = 2.011111;

iguana::to_json后打印出来:
{ "test": 2.011111E0}

@qicosmos
Copy link
Owner

这样问题不大吧,能正确反序列化就行。

@zyx199518
Copy link
Author

能否加一个控制浮点数有效数字的接口? 同时能够配置是否按照科学计数法显示?

@zyx199518
Copy link
Author

我们需要把序列化的浮点结果写到日志里面,需要控制打印的位数

@bbbgan
Copy link
Collaborator

bbbgan commented Apr 29, 2024

我们需要把序列化的浮点结果写到日志里面,需要控制打印的位数

打算提供一个接口,让用户可以自定义使用浮点数序列化,今天晚一点提PR

@bbbgan
Copy link
Collaborator

bbbgan commented Apr 30, 2024

#267 允许自定义浮点数的序列化,你可以参考example用snprintf。或者其他你满意的方法,具体用法可以merge之后参考 使用文档

@zyx199518
Copy link
Author

重载to_chars_float, 看上去编译完后buffer的位数已经确定, 后续有没有可能支持动态指定的方式,类似

StructData data;
std::string jsonStr
int floatPrecision = 5;
iguana::to_json(data, jsonStr, precision);

或者 其他能够基于当前代码实现的方案?

@bbbgan
Copy link
Collaborator

bbbgan commented May 6, 2024

那个buffer并不是实际的位数,只是最大容量,64位double + 一个结束字符 = 65。
目前如果希望做到动态的,最简单的方案是借助全局变量吧。
代码未测试,大概如下:

int floatPrecision = 5;
int doublePrecision = 10;

template <typename T>
inline char* to_chars_float(T value, char* buffer) {
    static_assert(std::is_floating_point<T>::value, "floating-point type needed");
    char format[16];
    if (std::is_same<T, float>::value) {
        std::snprintf(format, sizeof(format), "%%.%dg", floatPrecision);
    } else {
        std::snprintf(format, sizeof(format), "%%.%dg", doublePrecision);
    }
    int length = std::snprintf(buffer, 65, format, value);

    if (length == 0) {
        // throw
    }
    return buffer + length;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants