JAVA JOptionPane.showMessageDialog输出格式为十进制

时间:2013-02-07 22:59:52

标签: java swing joptionpane number-formatting decimalformat

我是Java的新手并且正在使用GUI显示消息。所以如果使用控制台

System.out.printf("Your total montly bill is $%.2f",  totalCost); 

以十进制的方式给出输出。我试图用这个做同样的事情,但是我得到更多的十进制数字,因为totalCost是一个类型double。如何将输出格式化为仅在小数后显示两位数?感谢。

JOptionPane.showMessageDialog(null, "Your monthly payment is " + totalCost);

4 个答案:

答案 0 :(得分:5)

你可以这样做:

JOptionPane.showMessageDialog(null, String.format("Your monthly payment is $%.2f",  totalCost));

答案 1 :(得分:3)

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
JOptionPane.showMessageDialog(null, "Your monthly payment is " + df.format(d));
System.out.println(df.format(d));

Class DecimalFormat API

答案 2 :(得分:1)

您也可以这样做:   JOptionPane.showMessageDialog(此,"您的每月付款为" + totalCost);

答案 3 :(得分:0)

DecimalFormat df = new DecimalFormat("#.##");
                String hour = JOptionPane.showInputDialog("Please input your hourly salary: ");
                double hr = Double.parseDouble(hour);
                double dr = hr * 8;             
                double wr = hr * 40;
                double mr = hr * 160;
                double yr = mr * 12;

    JOptionPane.showMessageDialog(null, "Yearly: " + df.format(yr) + " / " + "Monthly: "
                    + df.format(mr) + " / " + "Weekly: "+ df.format(wr) + " / " + "Hour: " + df.format(hr),
                    "Yearly Salary Calculator by the hour", JOptionPane.OK_OPTION, icon);