c12 c12 - 1 year ago 187
Java Question

Convert double to BigDecimal and set BigDecimal Precision

In Java, I want to take a double value and convert it to a

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);
//This prints 47.47999999999999687361196265555918216705322265625

It prints this huge thing:


and not


The reason I'm doing the
conversion is sometimes the double value will contain a lot of decimal places (i.e.
) and the when converting the double to a String will produce scientific notation
. 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?

Answer Source

It prints 47.48000 if you use another MathContext:

BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);

Just pick the context you need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download