Adding two doubles gives incorrect result?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

Looking at the following code ...

double a = 100.1;
double b = 0.1;
double c = a + b;

I would like to know why the value of c is 100.19999999999999 and not 100.2?

What should I do to correct this.

Thanks.
 
Floating point types (Float, Double) cannot hold exactly certain decimal
numbers. You could use the Decimal type if you need exact decimal
arithmetic, or use a subroutine package (e.g. GMP Bignum Library) if your
needed precision is greater than what Decimal can provide.

Or, you could do your arithmetic in floating point, convert the answer to
Decimal, and then round that to the precision you need.
 
It has to do with the way a PC stores floating point types. if one value
compared to the other is too much smaller, the computer "discards" part
of the smaller number leading to "errors" like this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top