JDK-8295391 : Add discussion of binary <-> decimal conversion issues
Type:Enhancement
Component:core-libs
Sub-Component:java.lang
Affected Version:20
Priority:P4
Status:Resolved
Resolution:Fixed
Submitted:2022-10-16
Updated:2024-10-27
Resolved:2023-11-18
The Version table provides details related to the release that this issue/RFE will be addressed.
Unresolved : Release in which this issue/RFE will be addressed. Resolved: Release in which this issue/RFE has been resolved. Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.
Binary <-> decimal conversion of floating-point values is common source of surprise. The core library documentation could outline the issues and how to avoid them.
Comments
A pull request was submitted for review.
Branch: master
URL: https://git.openjdk.org/jdk/pull/16566
Date: 2023-11-08 17:29:28 +0000
Relevant extract of Oracle Dev live "What Every Java Programmer Should Know About Floating-Point Arithmetic" September 2021:
* 0.1 is not exactly representable in binary; four-bit repeat after leading 0-bit.
* float values have 24 precision bits for approximation
* double values have 53 precision bits for approximation
* Therefore, 24 bits of the approximation to 0.1 will be less precise, and different than,
53 bits of an approximation to 0.1.:
* Exact decimal value of float approximation 0.1f:
0.100000001490116119384765625
(Leading 8 digits match exact value; recall: float good for 6 to 9 decimal digits)
* Exact decimal value of double approximation 0.1d:
0.1000000000000000055511151231257827021181583404541015625
(Leading 17 digits match exact value ; recall: double good for 15 to 17 decimal digits)
float approximation printed as a double value:
0.10000000149011612