Hi Jan,

to add to the other replies, it's a bit unfortunate that the doc of valueOf(double) suggests that this method should preferably be used to convert _float_ values as well.

You are right that your valueOf(float) would be a better fit, but again, that's hardly possible for source compatibility reasons after more than 20 years of valueOf(double) existence. Recompiling an existing source code that happens to invoke valueOf(double) with a float argument would suddenly change behavior for no apparent reasons.

One way out would be to add your method with a different name, like valueOfFloat(float) or similar, which would however break a long naming tradition of valueOf() conversion methods.


Greetings
Raffaello



On 2025-01-23 22:20, Jan Kowalski wrote:
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

Reply via email to