How to convert from float to bigDecimal in java?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With