【发布时间】:2015-10-28 20:56:15
【问题描述】:
我发现并修复了我的错误,我格式化了两次。
我正在尝试使用 JOptionPane 显示美元金额,但由于它是双精度的,因此我在小数点后得到了额外的数字。在 JOptionPane 中如何格式化?我尝试使用 String.format,但运行时出现错误;
线程“主”java.util.MissingFormatArgumentException 中的异常: 格式说明符'%.2f'
at java.util.Formatter.format(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.lang.String.format(Unknown Source) at CouponCalc.main(CouponCalc.java:38)
这是我的代码;
import javax.swing.JOptionPane;
public class CouponCalc {
public static void main(String[] args) {
double groceriesCost, discount;
double tier1=.08, tier2=.1, tier3=.12, tier4=.14; //coupon percentages for easy adjustment
groceriesCost = Double.parseDouble(JOptionPane.showInputDialog("Enter cost of groceries."));
if (groceriesCost<0)
{
JOptionPane.showMessageDialog(null, "Invalid Entry"); //TODO implement loop
System.exit(0);
}
else if (groceriesCost>=0 && groceriesCost<=9.99) //No coupon
JOptionPane.showMessageDialog(null, "You do not qualify for any coupons.)");
else if (groceriesCost>=10.00 && groceriesCost<=59.99) //tier 1 coupon
JOptionPane.showMessageDialog(null, String.format("You win a discount coupon of $" + String.format("%.2f", (groceriesCost*tier1)) +
". (8% of your purchase.)"));
else if (groceriesCost>=60.00 && groceriesCost<=149.99) //tier 2 coupon
JOptionPane.showMessageDialog(null, String.format("You win a discount coupon of $" + String.format("%.2f", (groceriesCost*tier2)) +
". (10% of your purchase.)"));
else if (groceriesCost>=150.00 && groceriesCost<=209.99) //tier 3 coupon
JOptionPane.showMessageDialog(null, String.format("You win a discount coupon of $" + String.format("%.2f", (groceriesCost*tier3)) +
". (12% of your purchase.)"));
else if (groceriesCost>=210.00) //tier 4 coupon
JOptionPane.showMessageDialog(null, String.format("You win a discount of $" + String.format("%.2f", (groceriesCost*tier4)) +
". (14% of your purchase.)"));
System.exit(0);
}
}
【问题讨论】:
-
NumberFormat.getCurrencyInstance().format(...
-
由于您在 AWT、servlet 或命令行应用程序中执行此操作的方式完全相同,因此它与 Swing 无关。
System.exit(0);..这在那时是多余的,因为退出 JRE 正是无论如何都会发生的事情。 -
“我运行它时遇到错误。”编辑您的问题以包含该错误的整个堆栈跟踪。
-
鉴于字体的性质,最好将 about 包装在 html 表格中,对于 example
标签: java string string-formatting currency