Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from float to bigDecimal in java?

How to convert from float to bigDecimal in java?

like image 211
akp Avatar asked Sep 30 '10 08:09

akp


People also ask

Is BigDecimal floating point?

Literal decimal floating-point numbers cannot always be precisely represented as an IEEE 754 floating-point value. Consequently, the BigDecimal(double val) constructor must not be passed a floating-point literal as an argument when doing so results in an unacceptable loss of precision.

What is the difference between float and BigDecimal data?

float and double are two primitive types, BigDecimal is a class. It doesn't just represent numbers but operations too. A float is a decimal numeric type represented with 32 bit. A double is a 64 bit decimal number, so it can represent larger values than a float.

Why would you use BigDecimal over float?

BigDecimal provides full control over the precision and rounding of the number value. Virtually, it's possible to calculate the value of pi to 2 billion decimal places using BigDecimal, with available physical memory being the only limit.


2 Answers

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.

like image 108
dogbane Avatar answered Oct 16 '22 19:10

dogbane


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)

like image 24
Spacemonkey Avatar answered Oct 16 '22 17:10

Spacemonkey