在Java窗格中格式化输出

时间:2014-01-25 23:44:04

标签: java format

我试图让java程序的输出正确格式化。该程序似乎正常工作。

[代码]

import javax.swing.JOptionPane;

public class Exercise4 {

    public static void main(String[] args) {
        double weight;
        double height;
        double bmi;
        String input;

        // Get users's weight.
        input = JOptionPane.showInputDialog("Enter your weight.");

        weight = Double.parseDouble(input);

        //Get users's height
        input = JOptionPane.showInputDialog("Enter your height in inches.");

        height = Double.parseDouble(input);

        bmi = weight * (703 / Math.pow(height, 2.0));

        JOptionPane.showMessageDialog(null, "Your BMI is  " + bmi);


    }

}

[/代码]

1 个答案:

答案 0 :(得分:1)

试试这个:

JOptionPane.showMessageDialog(null, String.format("Your BMI is %1.2f", bmi));

%1.2f将十进制数舍入为2位小数。

你应该看看format specifiers