how to output a double to 2 decmial places in a string?
Solution 1
Use format string %.2f
:
String.format(" %.2f", outputValue);
Solution 2
The accepted answer from Glenn Lane answers the question, how to do this correctly.
As for why the exception occurred, a careful search of the Formatter javadoc reveals this about the 0
flag:
Requires the output to be padded with leading zeros to the minimum field width following any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then a MissingFormatWidthException will be thrown.
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.
That's why %0.2f
throws a MissingFormatWidthException
, and %.2f
doesn't.
Solution 3
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on June 11, 2022Comments
-
Admin about 2 years
This program makes temperature conversions using an itemListener
outputValue is a protected double
outputString is also protected
output is a is a 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).