JsonCpp double
alibaba00 人气:0json文件里的值
程序代码
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位。
ps:JsonCpp的小数精度问题和插入输出顺序问题
直接说吧,这两个问题无法解决,如下:
官方不支持指定小数位数,double默认位宽为17位,如:"value" : 7.0999999999999996,
官方不支持按插入顺序输出,而是按照key的字母排序输出的,不管你什么顺序插入,下面的都是这样的顺序输出的:
"avg_abcdd " : 1.1632640000000014, "avg_pxczzczxczxd " : 7.0999999999999996, "avg_shczxcdize " : 802000.0, "deviccxz " : "shebei25", "sh323423fd " : 1420, "vcxzcasdasdadczco " : 231
个人应急想法
数字精度问题,可以考虑在C++中转为自己需求的精度,然后再当作字符串放到json中,至于之后的解析,读字符串再转数字即可;
顺序问题,两个想法:
1)不要用key,采用append的形式,也就是将每个条目放在一个容器中
Json::Value res; std::string = entry_str; entry_str.append("zhangsan,123"); entry_str.append("abc,2596"); ....... res["entry"] = entry_str;
2)那就按名字命令咯,顺应规则,2333333
加载全部内容