Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Casting Theory

1. ## 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:
```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:
```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.

2. ## 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.

3. ## The Following User Says Thank You to KevinWorkman For This Useful Post:

BigDru (October 25th, 2012)