Adding BigDecimal.valueOf(float val) constructor

Joseph D. Darcy joe.darcy at oracle.com
Thu Jan 23 23:50:39 UTC 2025


Hello,

On 1/23/2025 1:46 PM, Kevin Bourrillion wrote:
> Hi,
>
> Before addressing your request I want to try to just add a little 
> context as to what’s really going on (after which Joe will probably 
> correct me).


I'll augment Kevin's reply anyway :-)


> You might know some or all of this, but it’s a refresher for everyone 
> (including myself).


For some other quick background, please see the discussion of  "Decimal 
<-> Binary Conversion Issues" in the javadoc for java.lang.Double:

https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/lang/Double.html#decimalToBinaryConversion

In terms of concrete advice, if you want a BigDecimal equivalent to the 
string form of a float value, use the BigDecimal string constructor; e.g.

     float f = 0.1f;
     new BigDecimal(Float.toString(f)); // BigDecimal with a numerical 
value of 0.1

As Kevin noted, a numerical value of 0.1 is not the exact numerical 
value of the float value 0.1f, neither 0.1 the exact numerical value of 
0.1d, although the double value is much closer to 0.1.

For a more detailed explanation, my half-hour 2021 talk "What Every Java 
Programmer Should Know About Floating-Point Arithmetic" [1] covers this 
situation in more detail.

HTH,

-Joe

[1] 
https://cr.openjdk.org/~darcy/Presentations/OracleDevLive/OracleDevLive-2021-09-FloatingPoint.pdf
https://www.youtube.com/watch?v=ajaHQ9S4uTA



More information about the core-libs-dev mailing list