It’s not magic – it’s floating point math

Please remember that 3 / 12 is not always 0.25! 😉
Take this example:

int i = 3;
Console.WriteLine(i / 12);

You will get 0. I admit it could by a little confusing at first but I assure you, there is nothing wrong in the way JIT thinks. We dividing an integer over a… integer. What we are getting? Well, of course an integer! Is it not what you expected? How to fix this? Well the easiest way is to:

int i = 3;
Console.WriteLine(i / 12.0);

You will get 0.25. Why? Well 12.0 is a double so the whole equation will by a double. You can check this easily with:

object o = i / 12;
o = i / 12.0;

So we all have to pay for strong typing and it is in your best interest to remember that!
By the way

int i = 3;
int zero = 0;
Console.WriteLine(3 / 0);
Console.WriteLine(3 / zero);
Console.WriteLine(3.0 / zero);
Console.WriteLine(3.0 / 0);

3/0 won’t compile. 3/zero will throw an exception. 3.0/zero and 3.0/0 compile an run without a problem, they return +Infinity.

Oh, and one more thing (from my financial world of knowledge). 10% equals sometimes 11%!

int fullPrice = 100;
float discount = 0.1F;
Int32 finalPrice = (int)(fullPrice * (1-discount));
Console.WriteLine("The discounted price is ${0}.", finalPrice);

You will find this and other examples in good article about Floating Point in .NET.

Leave a Reply

Your email address will not be published. Required fields are marked *