Java 如何在字符串中输出双到 2 个十进制位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20177438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to output a double to 2 decmial places in a string?
提问by user2997509
This program makes temperature conversions using an itemListener
该程序使用 itemListener 进行温度转换
outputValue is a protected double
outputValue 是受保护的双精度值
outputString is also protected
outputString 也受到保护
output is a is a JTextField
输出是一个 JTextField
and output type is a protected 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);}
When I run the program I get:
当我运行程序时,我得到:
Exception in thread "AWT-EventQueue-0" java.util.MissingFormatWidthException: 0.2f,
with a long list of (unknown sources).
有一长串(来源不明)。
采纳答案by Glenn Lane
Use format string %.2f
:
使用格式字符串%.2f
:
String.format(" %.2f", outputValue);
回答by Henry
Try something like " %03.2f"
, the first 0 is just a flag to pad the number with leading zeros. It must be followed by a width specification.
尝试类似的方法" %03.2f"
,第一个 0 只是一个用前导零填充数字的标志。它必须跟在宽度规范之后。
回答by subash
try this..
尝试这个..
String outputType = " celsius";
DecimalFormat format = new DecimalFormat("###,###.##");
output.setText( format.format(Double.parseDouble(textField.getText()))+ outputType);
回答by Vinay Shukla
Hi the format you have chosen appears to be wrong the correct one would be
嗨,您选择的格式似乎是错误的,正确的格式是
outputString = String.format(" %.2f", outputValue);
回答by LarsH
The accepted answer from Glenn Lane answers the question, how to do this correctly.
从 Glenn Lane 接受的答案回答了这个问题,如何正确地做到这一点。
As for why the exception occurred, a careful search of the Formatter javadocreveals this about the 0
flag:
至于为什么会发生异常,仔细搜索Formatter javadoc揭示了关于0
标志的这一点:
Requires the output to be padded with leading zeros to the minimum field widthfollowing any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then a MissingFormatWidthException will be thrown.
要求输出用前导零填充到任何符号或基数指示符之后的最小字段宽度,除非转换 NaN 或无穷大。如果未提供宽度,则将抛出 MissingFormatWidthException。
So, %0.2f
is saying that the number should be padded with zeroes to n
places before the decimal (and 2 digits should be shown after the decimal). But n
is left unspecified.
所以,%0.2f
是说数字应该用零填充到 n
小数点之前的位置(并且小数点后应该显示 2 位数字)。但n
在未指定。
That's why %0.2f
throws a MissingFormatWidthException
, and %.2f
doesn't.
这就是为什么%0.2f
抛出 a MissingFormatWidthException
,而%.2f
不是。