Search code examples
javanumber-formattingtrim

How to format 18 digit double to become 10 string character


double pdouble= 3.3603335204002837E12;

String pstart= Double.toString(pdouble).replace(".", "") .trim()

String.format("%10d", pstart);

System.out.println("pstart"+pstart);

Can I know why it not works...
It display this:

Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.String at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302) .I

Hope anybody can help


Solution

  • %d is for int. As pstart is a String, Use b or s.

    String.format("%10s", pstart);
    

    Output

    33603335204002837E12
    

    Read Java String format()


    However if you need only the first 10 digits from your number, try using DecimalFormat

    DecimalFormat d = new DecimalFormat("0000000000");
    String number = d.format(pdouble);
    

    Output

    3360333520400
    

    This will also add leading 0s if the number is less than 10 digits.