System.out.println(2.6%1.1)// gives 0.39999999999
System.out.printf("%f",2.6%1.1)//gives 0.40000000
Anyone know why ?
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
Members have full access to the forums. Advertisements are removed for registered users.
System.out.println(2.6%1.1)// gives 0.39999999999
System.out.printf("%f",2.6%1.1)//gives 0.40000000
Anyone know why ?
Because floating point numbers have limited precision. So, when you calculate the modulus, the slight error due to the hardware limitations (known as the "ulp" or "unit in the last place") makes the number slightly off from exactly 0.4.
Printf is likely rounding off items within a few ulps so it prints out 0.4, but println doesn't so it prints out the number that's slightly off. This is also why using the == operator with floating points is very dangerous (and rather silly).
In the first case, the parameter numbers are treated as doubles (the default for primitive floating point numbers in java). The second instance it is being interpreted as a float. As an example:
Last edited by copeg; August 22nd, 2010 at 08:35 PM.
oh, well it's rounding off more than a few ulps
American (August 23rd, 2010)
Thanks to you all. Interesting....
Last edited by American; August 23rd, 2010 at 03:55 PM.
I actually didn't know this either. Thank you Copeg and HelloWorld922!