1

我对 Java 非常陌生,并且正在使用 GUI 显示消息。所以如果使用控制台

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

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

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

4 回答 4

6

你可以这样做:

JOptionPane.showMessageDialog(null, String.format("Your monthly payment is $%.2f",  totalCost));
于 2013-02-07T23:03:15.013 回答
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));

类 DecimalFormat API

于 2013-02-07T23:01:49.037 回答
1

你也可以这样做: JOptionPane.showMessageDialog(this, "你的月供是 " + totalCost);

于 2016-06-30T18:10:13.320 回答
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);
于 2015-01-11T03:02:43.413 回答