Java NumberFormat

时间:2013-03-27 00:17:50

标签: java number-formatting

我正在尝试在程序中使用java的 NumberFormat 类和 getPercentInstance 方法来计算税。我希望程序显示的是一个带有两位小数的百分比。现在,当我尝试将小数格式化为百分比之前,Java显示类似于0.0625的6%。如何让Java显示这样的小数或将0.0625称为“6.25%”?

代码片段:

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print("Enter the quantity of items to be purchased: ");
quantity = scan.nextInt();

System.out.print("Enter the unit price: ");
unitPrice = scan.nextDouble();

subtotal = quantity * unitPrice;
final double TAX_RATE = .0625;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;

System.out.println("Subtotal: " + fmt1.format(subtotal));
System.out.println("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE));
System.out.println("Total: " + fmt1.format(totalCost));

1 个答案:

答案 0 :(得分:9)

您可以使用NumberFormatsetMinimumFractionDigits(int)个实例上设置最小小数位数。

例如:

NumberFormat f = NumberFormat.getPercentInstance();
f.setMinimumFractionDigits(3);
System.out.println(f.format(0.045317d));

产地:

4.532%