How to convert from float to bigDecimal in java?

JavaFloating PointBigdecimal

Java Problem Overview


How to convert from float to bigDecimal in java?

Java Solutions


Solution 1 - Java

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 - Java

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)

Solution 3 - Java

For a precision of 3 digits after the decimal point:

BigDecimal value = new BigDecimal(f,
        new MathContext(3, RoundingMode.HALF_EVEN));

Solution 4 - Java

This is upto my knowledge :

   public static BigDecimal floatToBigDecimal(Float a){
	
	
	if(a == null || a.isInfinite() || a.isNaN()){
		return BigDecimal.ZERO;
	}
	try{
		return BigDecimal.valueOf(a);
		
	}catch(Exception e){
		return BigDecimal.ZERO;
	}
	
}

> *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).

public static BigDecimal valueOf(double val)

Parameters:
val - double to convert to a BigDecimal.
Returns:
a BigDecimal whose value is equal to or approximately equal to the value of val.
Throws:
NumberFormatException - if val is infinite or NaN.
Since:
1.5

I have checked whether Infinite or Not a Number, so that there is less chances of NumberFormatException

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionakpView Question on Stackoverflow
Solution 1 - JavadogbaneView Answer on Stackoverflow
Solution 2 - JavaSpacemonkeyView Answer on Stackoverflow
Solution 3 - JavaMaurice PerryView Answer on Stackoverflow
Solution 4 - JavaJohnny BlazeView Answer on Stackoverflow