System.out.println(2.6%1.1)// gives 0.39999999999
System.out.printf("%f",2.6%1.1)//gives 0.40000000
Anyone know why ?
Printable View
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:
oh, well it's rounding off more than a few ulps :P
Thanks to you all. Interesting....
I actually didn't know this either. Thank you Copeg and HelloWorld922!