C#拉扯Json双值加法异常?

时间:2017-06-22 19:02:57

标签: c# json double rounding addition

如标题所述,我从json字符串中提取大量值,替换“。”用“,”将它们转换成双倍并加起来。这里的异常似乎是,虽然字符串只包含2位数字,但endresult以.x9999999x结尾!如果您有任何解决方案或解释,我们表示赞赏。

小得多的JSON示例:

{"AK-47 | Aquamarine Revenge (Factory New)":"33.74","AK-47 | Aquamarine Revenge (Minimal Wear)":"23.35",
"AK-47 | Aquamarine Revenge (Field-Tested)":"17","AK-47 | Aquamarine Revenge (Well-Worn)":"14.5","AK-47 | Aquamarine Revenge (Battle-Scarred)":"11.7",
"StatTrak™ AK-47 | Aquamarine Revenge (Factory New)":"123.16","StatTrak™ AK-47 | Aquamarine Revenge (Minimal Wear)":"75.84","StatTrak™ AK-47 | Aquamarine Revenge (Field-Tested)":"54.2",
"StatTrak™ AK-47 | Aquamarine Revenge (Well-Worn)":"38.33","StatTrak™ AK-47 | Aquamarine Revenge (Battle-Scarred)":"31.24","AK-47 | Black Laminate (Factory New)":"91.3",
"AK-47 | Black Laminate (Minimal Wear)":"9.86","AK-47 | Black Laminate (Field-Tested)":"8.11","AK-47 | Black Laminate (Well-Worn)":"9","AK-47 | Black Laminate (Battle-Scarred)":"9.3",
"AK-47 | Bloodsport (Factory New)":"63.55","AK-47 | Bloodsport (Minimal Wear)":"55.7","AK-47 | Bloodsport (Field-Tested)":"49.35","AK-47 | Bloodsport (Well-Worn)":"48.31",
"StatTrak™ AK-47 | Bloodsport (Factory New)":"222.89","StatTrak™ AK-47 | Bloodsport (Minimal Wear)":"182.08"}

增值示例:

61241,69999998

编辑:

我将所有计算从Conver.ToDouble()更改为Convert.ToDecimal,现在似乎已修复。任何人都可以解释为什么另一个没有工作,虽然只有2位数字?

1 个答案:

答案 0 :(得分:3)

您必须反序列化为浮点数。如果是这样,字符串x.tr.children["foo"] = Node(title: "bar", leaf: false, children: [:]) // didChange: Node(title: "f", leaf: false, children: [ // "foo": kvc_in_playground.Node(title: "bar", leaf: false, children: [:]) // ]) 可能会转换为"61241,70"浮点值。将您的61241,69999998变量更改为float

这是因为decimal(和其他浮点类型)以数字二进制格式存储值,由于其精度有限,它们无法准确表示/存储某些十进制值。另一方面,float类型完全存储十进制值。

一个非常好的解释是here。该问题也在here进行了讨论,特别是在accepted answer

的第2点