0
public class MyClass {
 public static void main(String args[]) {
 float x=2.0f;
 float y=1.1f;
 System.out.println("Float = " + (x - y));
 double a=2.0d;
 double b=1.1d;
 System.out.println("Double = " + (a - b));
 }
}

Answer:

Float = 0.9
Double = 0.8999999999999999

I understand if I want better precision, I should have used BigDecimal, but why float (which is 32 bit with lesser precision compare to double) doesn't encounter the rounding issue?

asked Nov 13, 2017 at 6:19
1
  • It may happen that printing the function makes the rounding but the value is just approximated...and it is possible that printing a float and a double does not use the same routine. Commented Nov 13, 2017 at 6:28

1 Answer 1

1

I modified the code to print the exact value of each result immediately after the rounded value:

Float = 0.9
0.89999997615814208984375
Double = 0.8999999999999999
0.899999999999999911182158029987476766109466552734375

The double result is much, much closer to 0.9 than the float result. Those are the values that would have been used in any additional calculations.

The difference in the printout is a consequence of the Float and Double toString methods. Each aims to produce the shortest result that, on conversion back to the corresponding type, would produce the original value. 0.9 would convert to 0.89999997615814208984375 on float parsing. It would convert to 0.90000000000000002220446049250313080847263336181640625 on double parsing. It takes more digits to uniquely identify a double than a float.

answered Nov 13, 2017 at 14:09
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.