Java数字格式

Java数字格式,java,number-formatting,Java,Number Formatting,我试图在程序中使用java的NumberFormat类和getPercentInstance方法来计算税收。我希望程序显示一个带两位小数的百分比。现在,当我以前尝试将十进制设置为百分比时,Java显示了类似于0.0625的值,表示为6%。如何让Java显示这样的小数点,或者说0.0625为“6.25%” 代码片段: NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.ge

我试图在程序中使用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));

可以使用设置实例上小数位数的最小值

例如:

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

4.532%

您有
NumberFormat
,但我看不到您在任何地方使用它。