Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float data type precision in Java

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?

like image 767
ghoul932 Avatar asked Mar 11 '19 19:03

ghoul932


2 Answers

float x = 0.1f;
System.out.printf("%.17f", x);

0.10000000149011612
like image 192
M.N. Avatar answered Oct 10 '22 15:10

M.N.


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

like image 25
Peter Lawrey Avatar answered Oct 10 '22 15:10

Peter Lawrey