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:
decimal vs double! - Which one should I use and when?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With