How to convert from float to bigDecimal in java?
How to convert from float to bigDecimal in java?
Solution 1:
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.
Solution 2:
float f = 45.6f;
BigDecimal bd = BigDecimal.valueOf(f);
Quote from documentations:
Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).
Reference: BigDecimal (Java Platform SE 6)