千家信息网

JsonCpp中的double问题怎么解决

发表于:2024-10-18 作者:千家信息网编辑
千家信息网最后更新 2024年10月18日,本文小编为大家详细介绍"JsonCpp中的double问题怎么解决",内容详细,步骤清晰,细节处理妥当,希望这篇"JsonCpp中的double问题怎么解决"文章能帮助大家解决疑惑,下面跟着小编的思路
千家信息网最后更新 2024年10月18日JsonCpp中的double问题怎么解决

本文小编为大家详细介绍"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位。

ps:JsonCpp的小数精度问题和插入输出顺序问题

直接说吧,这两个问题无法解决,如下:

官方不支持指定小数位数,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问题怎么解决"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。

0