0

Why does this code produce the correct answer, except for the .000000001 at the end?

I have a DataGridView, that in a column has prices. This code goes down the grid, gets the values and adds them up.

double pp = 0;
for (int i = 0; i < PPUTDG.RowCount; i++)
{
    try
    {
      pp = pp + Convert.ToDouble(PPUTDG[16, i].Value.ToString().Replace("$",""));
    }
    catch { }
}

I then call .ToString() on pp. The values should add to 6240.75, except I get 6240.75000000001.

Thanks.

Lift
  • 546
  • 2
  • 4
  • 24

2 Answers2

4

There is a lot to be found about this. I already gave one, this: http://floating-point-gui.de/basic/ is another.

In short:

"...internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all."

Make sure you really need a floating point type. When dealing with money for example, it is better to use decimal or an integer and do your calculations in cents.

A good rule-of-thumb can be that it is OK to use a floating point type if the decimal-rounding errors are no problem in your application. Otherwise, use something else.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • 1
    I like it when problems are so easily solved, thanks! I'll accept your answer when the time limits up. – Lift Jul 09 '13 at 06:33
1

For financial calculations use decimal type instead of double or float types.

Eldar Agalarov
  • 4,849
  • 4
  • 30
  • 38