5

The value of the number 0.1 when stored as a single precision floating point number is 0.100000001490116119384765625 (source : https://www.h-schmidt.net/FloatConverter/IEEE754.html) but it is printed as 0.1 in Java. I think it happens because Java limits the number of decimal places in float to seven. How can I increase the number of decimal places displayed?

asked Mar 11, 2019 at 19:07
1

2 Answers 2

6
float x = 0.1f;
System.out.printf("%.17f", x);
0.10000000149011612
answered Mar 11, 2019 at 19:21
Sign up to request clarification or add additional context in comments.

Comments

4

You can show all the digits with BigDecimal.

System.out.println(new BigDecimal(0.1f));
System.out.println(new BigDecimal(0.1));

This shows the precise representation. float shows up to 24 digits and double shows up to 53 digits as this is the number of bits in the mantissa.

0.100000001490116119384765625
0.1000000000000000055511151231257827021181583404541015625

This avoids needing to work out how many digits to display.

System.out.println(new BigDecimal(0.125f));
System.out.println(new BigDecimal(0.125));

prints

0.125
0.125

as this value has no representation error as it is 2^-3

answered Mar 11, 2019 at 19:59

2 Comments

Note that BigDecimal doesn't follow IEEE-754
@LppEdd the data type itself doesn't but it does convert to/from double correctly.

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.