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?
float x = 0.1f;
System.out.printf("%.17f", x);
0.10000000149011612
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With