1

As described in the title im pulling a ton of values from a json string, replacing the "." with ",", converting them to double and adding them up. The anomaly here seems to be that while the string only contains numbers with 2 digits, the endresult ends with .x9999999x! If you have any fix or explanation, it is appreciated.

Much smaller JSON Example:

{"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"}

Added value example:

61241,69999998

EDIT:

I changed all calculations from Conver.ToDouble() to Convert.ToDecimal and now it seems to be fixed. Can anyone explain why the other one wasn't working although there are only 2-digit numbers??

1 Answers1

3

You must be deserializing to floating point numbers. If so the string "61241,70" may well be converted to the 61241,69999998 float value. Change your float variables to decimal.

This happens because float (and other floating-point types) store values in digital binary format, which cannot represent/store certain decimal values exactly given their limited precision. On the other hand, decimal type stores decimal values exactly.

A very good explanation is here. The issue is also discussed here, specifically in the point 2 of the accepted answer

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
  • I changed all calculations from `Conver.ToDouble()` to `Convert.ToDecimal` and now it seems to be fixed. Can you explain why the other one wasnt working? –  Jun 22 '17 at 19:25