项目中需要把conf.json文件中的浮点类型加载出来并放大100倍使用,但实际项目中遇到精度丢失的问题,比如浮点数是1078.60,加载出来后按常规逻辑 * 100 实际得到结果为 107859。精确度丢失了,为解决问题,我使用了下面简单方法避免了这种情况,而不需要使用类似GMP等高精度库。代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68using namespace std; //截取double小数点后2位,直接截断并乘以100转int64_t int64_t getDouble100(std::string const &s) { std::string::size_type npos = s.find_first_of('.'); if (npos != std::string::npos) { std::string prefix = s.substr(0, npos); std::string sufix = s.substr(npos + 1, -1); std::string x; if (!sufix.empty()) { if (sufix.length() >= 2) { x = prefix + sufix.substr(0, 2); } else { x = prefix + sufix.substr(0, 1) + "0"; } } return atoll(x.c_str()); } return atoll(s.c_str()) * 100; } // 想要把Json文件中的浮点数读取出来然后放大100倍 int main(int argc, char *argv[]) { //创建一个结构对象 boost::property_tree::ptree root; //读文件存放到root中 boost::property_tree::read_json<boost::property_tree::ptree>("./conf.json", root); double test = root.get<double>("test"); double fbalance = root.get<double>("data.balance"); double fbalance2 = root.get<double>("data.balance2"); // 想要的结果 int64_t _testValue = test * 100; int64_t _balanceValue = fbalance * 100; int64_t _balanceValue2 = fbalance2 * 100; std::cout << "===============正常处理结果=================="<< std::endl; std::cout << "test 想要得到的结果 107860" << std::endl; std::cout << "balance 想要得到的结果 107860" << std::endl; std::cout << "balance2 想要得到的结果 105860" << std::endl; std::cout << "实际得到的结果test:" << _testValue << std::endl; std::cout << "实际得到的结果balance:" << _balanceValue << std::endl; std::cout << "实际得到的结果balance2:" << _balanceValue2 << std::endl; std::cout << "===============经转字符串处理后=================="<< std::endl; // 转字符串 string testStr = to_string(test); string balanceStr = to_string(fbalance); string balance2Str = to_string(fbalance2); // 字符串再转整数 int64_t newTest = getDouble100(testStr); int64_t newBalance = getDouble100(balanceStr); int64_t newBalance2 = getDouble100(balance2Str); std::cout << "处理后得到的结果test:" << newTest << std::endl; std::cout << "处理后得到的结果balance:" << newBalance << std::endl; std::cout << "处理后得到的结果balance2:" << newBalance2 << std::endl; return 0; }
conf.json文件如下:
复制代码
1
2
3
4
5
6
7
8{ "data": { "balance":1078.60, "balance2":1058.60 }, "test": 1078.60 }
运行结果:
复制代码
1
2
3
4
5
6
7
8
9
10
11===============正常处理结果================== test 想要得到的结果 107860 balance 想要得到的结果 107860 balance2 想要得到的结果 105860 实际得到的结果test:107859 实际得到的结果balance:107859 实际得到的结果balance2:105859 ===============经转字符串处理后================== 处理后得到的结果test:107860 处理后得到的结果balance:107860 处理后得到的结果balance2:105860
最后
以上就是激情钢笔最近收集整理的关于c++加载json文件中double类型精度丢失解决方法的全部内容,更多相关c++加载json文件中double类型精度丢失解决方法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复