AlexmMikh AlexmMikh - 8 months ago 76
C# Question

Wrong parsing from string to double

double value = double.Parse("4655.927411110702", CultureInfo.InvariantCulture);

Why this parsing is getting me result: 4655.9274111107025?
Somehow it adds to my number 5 at the end. How should I convert this string to double and have a correct result?

Answer Source

You can't. Not all numbers can be represented exactly in double precision floating point, and the closest such double to 4655.927411110702 is 4655.927411110702450969256460666656494140625, and the default formatting you're using trims off the majority of the "joke" digits.

C# does have a decimal type. Can you not use that?

decimal value = decimal.Parse("4655.927411110702", CultureInfo.InvariantCulture);