2

I would like to add 0.01 to 36.01 and get 36.02 as the result But below code returns 36.019999999999994.

Double d = 36.01;
d = d + 0.01;

Could anyone tell me how to get 36.02 as the result ? Thanks in advance

rematnarab
  • 1,277
  • 4
  • 22
  • 42

4 Answers4

6

Use Decimal instead of Double. Decimal has higher accuracy and is recommended when, for instance, you're adding dollar amounts.

Here's a good previous SO post that will give you more details:

decimal vs double! - Which one should I use and when?

Community
  • 1
  • 1
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
3

That's because you are adding floating point numbers. 0.01 is the decimal fraction 1/100th, which cannot be exactly represented in binary in the available number of bits. Consider using the decimal type, or rounding to the desired precision using the appropriate Math.Round() overload and rounding style for your needs.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
2

You should use decimal as suggested. More importantly, you should read What Every Computer Scientist Should Know About Floating-Point Arithmetic to understand the underlying problem

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
0

double is double-precision floating number, decimal has more precision.

You should use decimal instead of.

decimal d = 36.01m;
d = d + 0.01m;
Console.WriteLine(d);

Here is a DEMO.

And of course I recommend you read to What Every Computer Scientist Should Know About Floating-Point Arithmetic

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364