本文小编为大家详细介绍“JsonCpp中的double问题怎么解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“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位。
直接说吧,这两个问题无法解决,如下:
官方不支持指定小数位数,double默认位宽为17位,如:"value" : 7.0999999999999996,
官方不支持按插入顺序输出,而是按照key的字母排序输出的,不管你什么顺序插入,下面的都是这样的顺序输出的:
"avg_abcdd " : 1.1632640000000014,
"avg_pxczzczxczxd " : 7.0999999999999996,
"avg_shczxcdize " : 802000.0,
"deviccxz " : "shebei25",
"sh423423fd " : 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
读到这里,这篇“JsonCpp中的double问题怎么解决”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。