Adding BigDecimal.valueOf(float val) constructor

Jan Kowalski jan7493 at gmail.com
Thu Jan 23 21:20:00 UTC 2025


Hi!

I’m currently working on a project that heavily relies on float values, and
we occasionally use BigDecimal for more precise mathematical operations.
However, I’ve noticed that the current BigDecimal constructor
implementation only supports double, which can lead to unintentional type
conversion and precision loss when creating a BigDecimal from a float.

The documentation suggests using BigDecimal.valueOf(double val) as the
preferred method for converting double or float values to BigDecimal, but
since method takes double as an argument, it leads much more often to
precision loss when float is passed.

For example:

- BigDecimal.valueOf(0.1d) correctly produces 0.1.

- However, BigDecimal.valueOf(0.1f) produces 0.10000000149011612, which
introduces unwanted precision artifacts.

What would you think about introducing a static factory method specifically
for float values, such as:

public static BigDecimal valueOf(float val) {
    return new BigDecimal(Float.toString(val));
}

This addition should improve usability and ensure that float values are
handled more precisely within the BigDecimal API
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250123/6d1678c9/attachment-0001.htm>


More information about the core-libs-dev mailing list