How to convert string to double without rounding error?

Asked

Viewed 1,820 times

5

Because the following command:

Convert.ToDouble("199998,99")

Results in:

199998.98999999

Already the command:

Convert.ToDouble("199998,98")

Results in:

199998.98000000001

?

  • The problem is in the return string conversation to double in some cases. For example Convert.Todouble("199998,99") results 199998.98999999999 Convert.Todouble("199998,98") results 199998.98000000001

  • Maybe this question be related

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

5

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

To solve this use the type decimal. He doesn’t have this problem. He has less performance but the difference is small or null in most situations.

There are several questions about this here with articles linked to give more details. No one should program on monetary or other values that need the exact value without fully understanding all implications.

This goes for any language. It is a characteristic 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 decimals. There’s nothing you can do. Some programmers think they’ve found the solution. But two most renowned computer scientists have spent a lot of time on this, they’ve tried everything, and there’s no solution but to use some other kind of data that gets the exact representation.

Places to start:

  • 1

    I didn’t know that, I’ll save it for when I need it. Very good.

  • I know that, thank you very much for pointing out, however I have to change a code snippet where you can’t change the type of variable, apparently they use Double for everything.

  • 3

    There is no real solution without changing the type of the variable, if the type of is wrong, it needs to be solved. I could tell you to use the decimal and then back to the double. Then the problem would happen. Changing in intermediate calculations can reduce the problem, but I don’t even know if I should. It can give the feeling that is better and error is error. Mistakes we correct. And this is very serious. If you don’t want to correct it, I feel sorry for whoever’s gonna use this app. Nothing else can be done but at least warn users that all values are unreliable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.