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
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
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:
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.
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
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