views:

91

answers:

7

How to convert from float to bigDecimal in java?

A: 

Use the constructor BigDecimal(double value):

float f = 1.5f;
BigDecimal d = new BigDecimal(f);
Confluence
it should be f = 1.5f;
org.life.java
A: 
new BigDecimal(myfloat)
leonm
A: 

Use contructor:

float f = 10.0f;
BigDecimal b = new BigDecimal(f);
krtek
+6  A: 
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.

dogbane
But converting a `float` to a String explicitly doesn't help you solve the unpredictability automatically - you need to take care to format the value correctly (rounding etc.).
Jesper
A: 

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);
Andreas_D
+1  A: 

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

Victor Ionescu
+1  A: 

For a precision of 3 digits after the decimal point:

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