Java – 格式化双倍值作为美元金额
我需要将双“amt”格式化为美元金额println(“$”+美元+“。”+美分),以便小数点后有两位数。
这样做的最佳方法是什么?
if (payOrCharge = 2) { System.out.println("Please enter the charged amount:"); double amt = keyboard.nextDouble(); cOne.addCharge(amt); System.out.println("-------------------------------"); System.out.println("The original balance is $" + cardBalance + "."); System.out.println("You added a charge in the amount of " + amt + "."); System.out.println("The new balance is " + (cardBalance + amt) + "."); }
使用NumberFormat.getCurrencyInstance() :
double amt = 123.456; NumberFormat formatter = NumberFormat.getCurrencyInstance(); System.out.println(formatter.format(amt));
输出:
$123.46
您可以使用DecimalFormat
DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(amt));
这将为您提供始终2dp的打印输出。
但实际上,由于浮点问题,你应该使用BigDecimal来赚钱
使用DecimalFormat
以所需格式打印十进制值,例如
DecimalFormat dFormat = new DecimalFormat("#.00"); System.out.println("$" + dFormat.format(amt));
如果您希望以美国数字格式显示$ amount,请尝试:
DecimalFormat dFormat = new DecimalFormat("####,###,###.00"); System.out.println("$" + dFormat.format(amt));
使用.00
,它总是打印两个小数点而不管它们的存在。 如果只想存在十进制数,则在格式字符串中使用.##
。
您可以将printf用于单个衬垫
System.out.printf("The original balance is $%.2f.%n", cardBalance);
这将始终打印两个小数位,根据需要进行舍入。
对货币类型使用BigDecimal而不是double。 在Java Puzzlers一书中,我们看到:
System.out.println(2.00 - 1.10);
你可以看到它不会是0.9。
String.format()具有格式化数字的模式。