简体   繁体   中英

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

%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 0 s if the number is less than 10 digits.

For decimal numbers "f" flag needs to be used.

double pdouble= 3.3603335204002837E12;

System.out.println(String.format("%10f", pdouble));

This will print a string with minimum length of 10 chars.

In this pattern "%10f" the width flag (eg 10) is the minimum number of characters

The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.

from Formatter java doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM