# Casting Theory

• October 25th, 2012, 08:11 AM
BigDru
Casting Theory
I came across something interesting in my book and I'm unsure as to why this is happening. Here is some sample code:
Code :

```public class DividingWithDifferentTypes { public static void main(String args[]) { int iVar = 15; long lVar = 2; float fVar = 7.6f - iVar / lVar; double dVar = 1L / lVar + fVar / lVar; int result = (int) (100 * dVar); System.out.println(iVar / lVar); System.out.println(7.6f); System.out.println((float) (iVar / lVar)); System.out.println(7.6f - (float) (iVar / lVar)); System.out.println(1L / lVar); System.out.println(fVar / lVar); System.out.println(100 * dVar); System.out.println(result); } }```

And here is the output:
Code :

```7 7.6 7.0 0.5999999 0 0.29999995 29.999995231628418 29```

My confusion arises from the fact that the 4th output statement returns 0.5999999F instead of 0.6F.
Why is this happening? I'm assuming it has to do with casting. Thank you in advance.
• October 25th, 2012, 08:21 AM
KevinWorkman
Re: Casting Theory
Basically, it comes down to how decimals are stored in binary. You can only get so much precision out of it, so it's oftentimes off buy just a tiny bit. For more information, google "what every computer scientist should know about floating point arithmetic" for the go-to article explaining exactly what's happening.