所以我已经完成了另一个上课程序,并且正在尝试使其看起来更“不错”。我已经对每个问题和选择都使用了JOptionPane,但是输出了...是否有一种方法可以像System.ou.print一样使用J窗格将答案输出到小数点后2位?
仅发布一种方法的一部分代码
public static void Celsius()
//First method used within Start to convert Celsius to Fahrenheit
{
double converted;
double temperature;
//user inputs temperature to be converted
temperature = Double.parseDouble(JOptionPane.showInputDialog(null,
"Please enter the temperature in Celsius and press 'Ok'",
"You selected Celsius to Fahrenheit",
JOptionPane.INFORMATION_MESSAGE));
converted = 9/5.0*temperature+32;
//outputs converted temperature
System.out.print("The converted temperature in Fahrenheit = ");
System.out.printf(" %.2f", converted);
System.out.println(" degrees Fahrenheit");
}
答案 0 :(得分:2)
您正在寻找DecimalFormat(另请参见here)
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.456345);
JOptionPane.showMessageDialog(null, "Result: " + formatted); // shows 2.46