How to convert from float to bigDecimal in java?

akp picture akp · Sep 30, 2010 · Viewed 65.7k times · Source

How to convert from float to bigDecimal in java?

Answer

dogbane picture dogbane · Sep 30, 2010
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.