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?
You want to try
String.format("%f", d)
, which will print your double in decimal notation. Don't useBigDecimal
at all.Regarding the precision issue: You are first storing
47.48
in thedouble c
, then making a newBigDecimal
from thatdouble
. The loss of precision is in assigning toc
. You could doto avoid losing any precision.
The String.format syntax helps us convert doubles and BigDecimals to strings of whatever precision.
This java code:
Prints: