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", "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
到此這篇關於JsonCpp中double的問題解決的文章就介紹到這瞭,更多相關JsonCpp double內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- C語言如何把浮點數轉換為字符串
- JavaScript中極易出錯的操作符運算總結
- JavaScript數據結構Number
- C++ qt 使用jsoncpp json 讀寫操作
- Java學習筆記:關於Java double類型相加問題