Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Precision when a float value is passed in double

I have on question regarding double precision.When a float value is passed into double then I get some different result. For e.g.

float f= 54.23f;
double d1 = f;
System.out.println(d1);

The output is 54.22999954223633. Can someone explain the reason behind this behaviour. Is it like double defaults to 14 places of decimal precision.

like image 345
Hitesh Avatar asked May 09 '26 15:05

Hitesh


1 Answers

The same value is printed differently for float and double because the Java specification requires printing as many digits as needed to distinguish the value from adjacent representable values in the same type (per my answer here, and see the linked documentation for more precision in the definition).

Since float has fewer bits to represent values, and hence fewer values, they are spaced more widely apart, and you do not need as many digits to distinguish them. When you put the value into a double and print it, the Java rules require that more digits be printed so that the value is distinguished from nearby double values. The println function does not know that the value originally came from a float and does not contain as much information as can fit into a double.

54.23f is exactly 54.229999542236328125 (in hexadecimal, 0x1.b1d70ap+5). The float values just below and just above this are 54.2299957275390625 (0x1.b1d708p+5) and 54.23000335693359375 (0x1.b1d70cp+5). As you can see, printing “54.23” (the result of rounding to six digits after the decimal point, making 54.230000, and removing the trailing zeros) would distinguish the value from 54.229995… and from 54.23…. However, the double values just below and just above 54.23f are 54.22999954223632101957264239899814128875732421875 and 54.22999954223633523042735760100185871124267578125. To distinguish the value, you need “54.22999954223633”.

like image 84
Eric Postpischil Avatar answered May 11 '26 05:05

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!