如何将18位双精度格式化为10个字符串字符

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);

我能知道为什么它不起作用吗...
它显示这个:

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

希望有人能帮忙

%d 适用于 int。由于 pstart 是字符串,因此使用 bs.

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

输出

33603335204002837E12

阅读Java String format()


但是,如果您只需要号码的前 10 位数字,请尝试使用 DecimalFormat

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

输出

3360333520400

如果数字少于 10 位,这也会添加前导 0

对于十进制数 "f" 需要使用标志。

double pdouble= 3.3603335204002837E12;

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

这将打印一个最小长度为 10 个字符的字符串。

在此模式“%10f”中,宽度标志(例如 10)是最小字符数

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.

来自 Formatter java 文档