C# – Modulus operator with decimal values

I came across this thing yesterday and wanted to share it with others.

If you use a modulus operator in C# with decimal values, the result can be quite interesting.


0.27 % 0.05 will return 0.02 as expected.

However, if you retrieve the value 0.27 from a textbox and convert into a double then …… the result will not be 0.02! This is because C# consider the 0.27 value retrieved from textbox as 0.2700000000….. And now when you use %(modulus),  it tries to give you a very accurate result. Something like 0.019999999967.  If rounded using Math.Round(), it will give 0.02.

So we need to be aware about this otherwise, all our future calculations based on this value(without knowing the accurary which C# tries to provide) will go wrong.

The way i tried to solve this problem was to convert the double to an integer value by multiplying it with 100 i.e. 0.27 * 100 = 27. Then doing all my calculations with whole number and the final result can again be decimalised.  But in doing this, make sure you use Convert.ToInt() instead of typecasting the result directly by (int) i.e. use Convert.ToInt32(0.27 * 100) and NOT (int) 0.27 * 100.

Finally, to force it to remain as a two decimal number, you can use .ToString(“0.00”)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s