Advertisement
Advertisement


Convert Double to String value preserving every digit


Question

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"

2011/11/01
1
5
11/1/2011 10:39:12 AM

Accepted Answer

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
    }
}
2011/11/01
7
11/1/2011 10:42:09 AM


Try String.format("%20.0f", 9.01236789E9)

Note though it's never an exact value, so "preserving every digit" doesn't really make sense.

2011/11/01

In this case, you can also do

double value = 9.01236789E9;
System.out.println((long) value); // prints 9012367890
2011/11/01

You can use it.

String doubleString = Double.toString(inValue)

inValue -----> Described by you.to what position you want to Change double to a string.

2011/11/01

Source: https://stackoverflow.com/questions/7965190
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]