jsoncpp使用过程中发现double精度
- json文件里的值
- 程序代码
new_item["Voltage"] = 8.622;
new_item["Current"] = 8.63456;
new_item["Energy"] = 8.234234;
- 程序运行结果
- Jsoncpp的json_write.cpp中
std::string valueToString(double value, bool useSpecialFloats, unsigned int precision) {
// Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below.
char buffer[32];
int len = -1;
char formatString[6];
sprintf(formatString, "%%.%dg", precision);
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), formatString, value);
} else {
// IEEE standard states that NaN values will not compare to themselves
if (value != value) {
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
} else if (value < 0) {
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
} else {
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
}
// For those, we do not need to call fixNumLoc, but it is fast.
}
assert(len >= 0);
fixNumericLocale(buffer, buffer + len);
return buffer;
}
这里sprintf(formatString, “%%.%dg”, precision);的结果是“%.17g”。是输出17位的有效数字。不足的补足17位。