How to convert string to double without rounding error?

5

Because the following command:

Convert.ToDouble("199998,99")

Results in:

  

199998.98999999999

Already the command:

Convert.ToDouble("199998,98")

Results in:

  

199998.98000000001

?

    
asked by anonymous 31.07.2015 / 14:47

1 answer

5

Assuming the culture is right and can use the comma (it seems like it), the problem is that the numerical rounding of type double . Unfortunately most programmers do not understand its usage and do not know that it can not be used for numerical accuracy, it can not be used for monetary values.

To resolve this use the type decimal . He does not have this problem. It has less performance but the difference is minor or null in most situations.

You have several questions about this here with linked articles to give more details. No one should program over monetary or other values that need the exact value without completely understanding all of the implications.

This holds true for any language. It is a feature of the processor. The type double , or even float uses the binary form to represent the number and this prevents it from representing all numbers with decimal places. There is nothing that can be done. Some programmers think they have found the solution. But two more renowned computer scientists have spent a lot of time on this, have tried everything and there is no solution other than to use another type of data to achieve exact representation.

Starting places:

31.07.2015 / 14:57