如何在一个字符串中输出一个double到2个decmial位置?

use*_*509 2 java formatting decimal

该程序使用itemListener进行温度转换

outputValue是受保护的double

outputString也受到保护

输出是一个JTextField

和输出类型是受保护的char

public void itemStateChanged(ItemEvent e) {
    inputValue =  Double.parseDouble(textField.getText());

    //the input value is converted to the outputValue based on the outputType

    outputString = String.valueOf(outputValue);            //set output value to string
    outputString = String.format(" %0.2f", outputValue);   //format to .00

    output.setText( outputString + (char) 0x00B0 + outputType);}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,我得到:

Exception in thread "AWT-EventQueue-0" java.util.MissingFormatWidthException: 0.2f,
Run Code Online (Sandbox Code Playgroud)

有很多(未知来源).

Gle*_*ane 12

使用格式字符串%.2f:

String.format(" %.2f", outputValue);
Run Code Online (Sandbox Code Playgroud)


Lar*_*rsH 5

从 Glenn Lane 接受的答案回答了这个问题,如何正确地做到这一点。

至于为什么会发生异常,仔细搜索Formatter javadoc揭示了关于0标志的这一点:

要求输出用前导零填充任何符号或基数指示符之后的最小字段宽度,除非转换 NaN 或无穷大。如果未提供宽度,则将抛出 MissingFormatWidthException。

所以,%0.2f是说数字应该用零填充到 n小数点之前的位置(并且小数点后应该显示 2 位数字)。但n在未指定。

这就是为什么%0.2f抛出 a MissingFormatWidthException,而%.2f不是。