Advertisement
Advertisement


Converting a double to exact string in java


Question

I have the following double value

double d = 123456789.8210000000001;

Now I need to convert it to

String s = "123456789.8210000000001"

exactly.

I used the following code

double d = 123456789.8210000000001d;
DecimalFormat df = new DecimalFormat();
df.setGroupingUsed(false);
df.setMaximumIntegerDigits(20);
df.setMaximumFractionDigits(20);
System.out.println(df.format(d));

but it gives the output "123456789.821"

When I used the following code

double d = 123456789.8210000000001d;
BigDecimal bd = new BigDecimal(d);
System.out.println(bd.toPlainString());

it gives 123456789.82099999487400054931640625

but I need the exact value.

Note: Here the number of digits in the Integer/fraction part can vary.

2014/07/16
1
0
7/16/2014 9:11:07 AM


When you define it as double that change will happen. use BigDecimal

    BigDecimal val = new BigDecimal("123456789.8210000000001");
    String str=val.toString();
    System.out.println(str);

Now you will get the same as String

Output:

   123456789.8210000000001