Java NumberFormat

二次信任 提交于 2020-01-04 04:10:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!