C# Pulled Json Double-Values 添加异常?

C# Pulled Json Double-Values addition anomaly?

如标题中所述,我从 json 字符串中提取了大量值,替换了“.”使用“,”,将它们转换为双精度并将它们相加。这里的异常似乎是,虽然字符串只包含 2 位数字,但最终结果以 .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 位数字?

您必须反序列化为浮点数。如果是这样,字符串 "61241,70" 很可能会转换为 61241,69999998 浮点值。将 float 变量更改为 decimal.

发生这种情况是因为 float(和其他浮点类型)以数字二进制格式存储值,这不能 represent/store 某些十进制值恰好给定其有限的精度。另一方面,decimal 类型准确地存储十进制值。

一个很好的解释是here. The issue is also discussed here, specifically in the point 2 of the accepted answer