In Java, I want to take a double value and convert it to a BigDecimal
and print out its String value to a certain precision.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double d=-.00012;
System.out.println(d+""); //This prints -1.2E-4
double c=47.48000;
BigDecimal b = new BigDecimal(c);
System.out.println(b.toString());
//This prints 47.47999999999999687361196265555918216705322265625
}
}
It prints this huge thing:
47.47999999999999687361196265555918216705322265625
and not
47.48
The reason I'm doing the BigDecimal
conversion is sometimes the double value will contain a lot of decimal places (i.e. -.000012
) and the when converting the double to a String will produce scientific notation -1.2E-4
. I want to store the String value in non-scientific notation.
I want to have BigDecimal always have two units of precision like this: "47.48". Can BigDecimal restrict precision on conversion to string?
It prints 47.48000 if you use another MathContext:
Just pick the context you need.
Why not :
In Java 9 the following is deprecated:
BigDecimal.valueOf(d).
setScale(2, BigDecimal.
ROUND_HALF_UP);
instead use:
Example:
The reason of such behaviour is that the string that is printed is the exact value - probably not what you expected, but that's the real value stored in memory - it's just a limitation of floating point representation.
According to javadoc, BigDecimal(double val) constructor behaviour can be unexpected if you don't take into consideration this limitation:
So in your case, instead of using
use
Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of
Double.toString(double)
.It's printing out the actual, exact value of the
double
.Double.toString()
, which convertsdouble
s toString
s, does not print the exact decimal value of the input -- ifx
is your double value, it prints out exactly enough digits thatx
is the closestdouble
to the value it printed.The point is that there is no such
double
as 47.48 exactly. Doubles store values as binary fractions, not as decimals, so it can't store exact decimal values. (That's whatBigDecimal
is for!)