首页 > 解决方案 > JOptionPane 输出双至 2 位小数:

问题描述

所以我已经完成了另一个课程计划,并试图让它看起来更“好”一点。我对每个问题和选择都使用了 JOptionPane,但输出...有没有办法使用 J-pane 将答案输出到 System.ou.print 的小数点后 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");
}

标签: java

解决方案


您正在寻找DecimalFormat(另请参阅此处

DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.456345); 
JOptionPane.showMessageDialog(null, "Result: " + formatted);   // shows 2.46

推荐阅读