2013-03-27 63 views
3

我試圖使用Java的的NumberFormat類和getPercentInstance方法在一個程序來計算稅收。我想要程序顯示的是有兩位小數的百分比。現在,當我嘗試將百分比格式化爲百分比之前,Java顯示了0.0625這樣的6%。我如何讓Java顯示一個小數點,或者說0.0625爲「6.25%」?的Java的NumberFormat

的代碼片段:

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)); 
+3

你有'NumberFormat',但我沒有看到你在任何地方使用它。 – Makoto 2013-03-27 00:18:38

回答

9

您可以設置使用setMinimumFractionDigits(int)一個NumberFormat實例的小數的最小數量。

例如:

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

產地:

4.532% 
+1

它工作完美,謝謝 – ST33L 2013-03-27 00:36:14