Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Double to String value preserving every digit

How do I convert a double value with 10 digits for e.g 9.01236789E9 into a string 9012367890 without terminating any of its digits ?

I tried 9.01236789E9 * Math.pow(10,9) but the result is still double "9.01236789E18"

like image 651
Mohsin Avatar asked Nov 01 '11 10:11

Mohsin


2 Answers

    double d = 9.01236789E9;    
    System.out.println(BigDecimal.valueOf(d).toPlainString());
like image 108
Prince John Wesley Avatar answered Oct 10 '22 03:10

Prince John Wesley


While 10 digits should be preservable with no problems, if you're interested in the actual digits used, you should probably be using BigDecimal instead.

If you really want to format a double without using scientific notation, you should be able to just use NumberFormat to do that or (as of Java 6) the simple string formatting APIs:

import java.text.*;

public class Test
{
    public static void main(String[] args)
    {
        double value = 9.01236789E9;
        String text = String.format("%.0f", value);
        System.out.println(text); // 9012367890

        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(0);
        format.setGroupingUsed(false);
        System.out.println(format.format(value)); // 9012367890
    }
}
like image 41
Jon Skeet Avatar answered Oct 10 '22 05:10

Jon Skeet