How to convert from float to bigDecimal in java?
Use the constructor BigDecimal(double value)
:
float f = 1.5f;
BigDecimal d = new BigDecimal(f);
BigDecimal value = new BigDecimal(Float.toString(123.4f));
From the javadocs, the string constructor is generally the preferred way to convert a float
into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double)
constructor.
Quote from the docs:
Note: For values other float and double NaN and ±Infinity, this constructor is compatible with the values returned by Float.toString(float) and Double.toString(double). This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.
Converting from float
to BigDecimal
, in other words: casting? impossible. But you can create an instance of BigDecimal
that represents the same fractional value like the float value:
BigDecimal number = new BigDecimal(floatValue);
There are two ways:
First, the recommended way:
float f = 0.2f;
BigDecimal bd = new BigDecimal(f);
but if you print the big decimal it displays 0.20000000298023224, which might not satisfy the needs of your program.
Another way:
float f = 0.2f;
BigDecimal bd = new BigDecimal(String.valueOf(f));
and if you print the big decimal it displays 0.2
For a precision of 3 digits after the decimal point:
BigDecimal value = new BigDecimal(f,
new MathContext(3, RoundingMode.HALF_EVEN));