1

So I'm having a trouble formatting a String.

My output should always be ##.##C or F (temperature conversion)

so here is my method:

public void setResultLabel(double inNumber, char inChar)
{   

    String number, letter;

    number = String.valueOf(inNumber);

    letter = String.valueOf(inChar);

    String temp;

    temp = number + letter;

    String format = String.format("%2.5s", temp); /* how do you make this code 
    so that the out put result will always be up to two decimal places 
    with a char C or F? */

    result.setText(format);

    add(result);
}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60

3 Answers3

1
public void setResultLabel(double inNumber, char inChar)
{   

    String number, letter;
    DecimalFormat decimalFormat = new DecimalFormat("##.##"+inChar);


    String formated = decimalFormat.format(inNumber); 
    /* formated  is your result  */
    // System.out.println(formated);

    result.setText(format);
    add(result);
}
Saif
  • 6,804
  • 8
  • 40
  • 61
0

Use DecimalFormat to format decimal numbers. To change the decimal mark from a "," to a "." (if needed), use DecimalFormatSymbols

public void setResultLabel(double inNumber, char inChar) {   
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    DecimalFormat df = new DecimalFormat("##.##");
    df.setDecimalFormatSymbols(dfs);

    result.setText(df.format(inNumber) + inChar);
    add(result);
}

Note that usually DecimalFormat would be a field in your class since you don't want to create a new DecimalFormat and a new DecimalFormatSymbols every time you call the setResultLabel() method.

Marv
  • 3,517
  • 2
  • 22
  • 47
0

You can achieve the desired result using following code snippet.

double p =10.1234;
char s = 'F';
String formatted = String.format("%.2f%S", p, s);
System.out.println(formatted);

You can find more information about formatting at oracle. Note that there are other alternatives as well to achieve the output, you can find the useful links here.

CuriousMind
  • 3,143
  • 3
  • 29
  • 54