Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to output a double to 2 decmial places in a string?

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

like image 641
user2997509 Avatar asked Nov 24 '13 17:11

user2997509


2 Answers

Use format string %.2f:

String.format(" %.2f", outputValue);
like image 69
Glenn Lane Avatar answered Oct 22 '22 11:10

Glenn Lane


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.

like image 41
LarsH Avatar answered Oct 22 '22 10:10

LarsH