Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many decimals after addition

Tags:

c#

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

like image 483
rematnarab Avatar asked Sep 13 '25 06:09

rematnarab


2 Answers

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?

like image 73
Grant Winney Avatar answered Sep 15 '25 22:09

Grant Winney


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.

like image 26
Nicholas Carey Avatar answered Sep 15 '25 22:09

Nicholas Carey