float data type precision in Java

ghoul932 :

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?

Peter Lawrey :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74582&siteId=1