Questions about Float.toString(float)
Raffaello Giulietti
raffaello.giulietti at oracle.com
Mon Jun 6 16:36:41 UTC 2022
On 2022-06-05 09:59, LP wrote:
> Hi,
>
> (1)
> float f = Float.intBitsToFloat(260046848);
>
> JDK 17: Float.toString(f) -> 1.26217745E-29
> master: Float.toString(f) -> 1.2621775E-29
>
> BigDecimal.valueOf(Float.intBitsToFloat(260046847)) -> 1.2621773731219804E-29
> BigDecimal.valueOf(Float.intBitsToFloat(260046848)) -> 1.2621774483536189E-29
> BigDecimal.valueOf(Float.intBitsToFloat(260046849)) -> 1.2621775988168958E-29
>
> What about 1.2621774E-29? I believe both 1.2621774E-29 and 1.2621775E-29 satisfy the Javadoc of Float.toString(float), so maybe it doesn't matter, but 1.2621774E-29 is closer to f.
>
In addition to f above, let
float g = Float.intBitsToFloat(260046847);
Then
f == 1.2621775E-29f -> true
g == 1.2621774E-29f -> true
Hence, 1.2621774E-29f rounded to the closest float is g, not f.
1.2621775E-29f is indeed the shortest decimal that rounds to f. Other
equally long decimals like 1.2621774E-29f or 1.2621776E-29f do not round
to f but to other floats.
So, no, 1.2621774E-29 does not satisfy the spec for f. Only
1.2621775E-29 does.
> (2)
> float f = Float.intBitsToFloat(1291845637);
>
> JDK 17: Float.toString(f) -> 1.34217808E8
> master: Float.toString(f) -> 1.3421781E8
>
> BigDecimal.valueOf(Float.intBitsToFloat(1291845636)) -> 134217792
> BigDecimal.valueOf(Float.intBitsToFloat(1291845637)) -> 134217808
> BigDecimal.valueOf(Float.intBitsToFloat(1291845638)) -> 134217824
>
> What about 1.342178E8? 1.3421781E8 is an improvement over 1.34217808E8, but it's still not conforming to the Javadoc if 1.342178E8 is valid.
>
Again, 1.342178E8f < 1.3421781E8f, so these are decimals representing
two different floats. Only 1.3421781E8f rounds to your f, whereas
1.342178E8f rounds to
float g = Float.intBitsToFloat(1291845636);
> Apologies if I misunderstood something.
>
> Thanks,
> LP
More information about the core-libs-dev
mailing list