Java 数字格式

标签 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));

最佳答案

您可以在 NumberFormat 上设置最小小数位数使用 setMinimumFractionDigits(int) 的实例.

例如:

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

产生:

4.532%

关于Java 数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15649833/

相关文章:

Java - 销毁正在做某事的对象

java - Java 中的对象是否有任何内存大小限制?

java - ChoiceFormat.setChoices 关于格式参数类型和文档的混淆

PowerShell,格式化另一种文化中的值

php - substr 以逗号生效

.net - 为什么 Convert.ToInt32 接受 IFormatProvider?

java - Android View 添加 child

java - Java声明数组。有什么区别?

haskell - 如何从 Double 而不是 Haskell 中的科学记数法中获取十进制字符串?

java - 无法反序列化 Spring Session Scoped bean