问题
I'm trying to use java's NumberFormat class and the getPercentInstance method in a program to calculate tax. What I want the program to display is a percentage with two decimal places. Now, when I tried to format a decimal as a percent before, Java displayed something like 0.0625 as 6%. How do I make Java display a decimal like that or say 0.0625 as "6.25%"?
Code Fragment:
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:
You can set the minimum number of fraction digits on a NumberFormat instance using setMinimumFractionDigits(int).
For instance:
NumberFormat f = NumberFormat.getPercentInstance();
f.setMinimumFractionDigits(3);
System.out.println(f.format(0.045317d));
Produces:
4.532%
来源:https://stackoverflow.com/questions/15649833/java-numberformat