javaformattingdecimal

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


Solution

  • Use format string %.2f:

    String.format(" %.2f", outputValue);