Incorrect double sum of values!

Asked

Viewed 82 times

2

In a client the sum of 10 lines in a table should total 100. The problem is that the reported values total 100 however when adding, even if fail in the code to avoid garbage coming from the application the sum does not close.

inserir a descrição da imagem aqui

Note that the error is more than 10 decimal places, and I worked with a maximum of 4. I would like to avoid a rounding since the sum should simply work.

Any suggestions?

  • I am curious to know the answer. This also happens in PHP, if I inform in a variable the value 16.8, giving a print appears 16.79999

  • One of the most famous articles in computing is called "What Every Computer Scientist Should Know About Floating-Point Arithmetic". Reading it allows us to understand the reason for this. The site http://floating-point-gui.de/, summarizes the article very well. This answer deserves to be well elaborated and I’m running out of time for that at the moment. Certainly some of Sopt’s beasts like bigown, Luiz Vieira, among others are already making a beautiful answer. :-)

  • Strange, if you have the number displayed on the screen by Console.WriteLine(lValor) It shows 100 straight.

  • 2

    @Meuchapeu because the hour that converts to string to print has a calculation, in this case ended up rounding up the expected way but it is pure coincidence, nothing guarantees that it will always be like this. --- I closed it by duplicate, because it already has the explanation of why there is this error for all languages. There is no reason to duplicate questions that in the background the answer, do not use double when you need accuracy and be happy.

  • As @Cantoni quoted, there is an explanation and the idea is that double and float are not exactly accurate. The solution to my case was to instantiate the value as decimal instead of double.

No answers

Browser other questions tagged

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