2012-10-28 212 views
2

System.printf(「%。2f」,currentBalance)工作正常,但問題出現在句子後面的舍入數字。把代碼放到你的eclipse程序中並運行它,你可以看到一些肯定是錯誤的。如果有人能幫助它,將不勝感激。嘗試在java中舍入到小數點後兩位數

public class BankCompound { 


public static void main (String[] args) { 
    compound (0.5, 1500, 1); 
} 

public static double compound (double interestRate, double currentBalance, int year) { 

    for (; year <= 9 ; year ++) { 

    System.out.println ("At year " + year + ", your total amount of money is "); 
    System.out.printf("%.2f", currentBalance); 
    currentBalance = currentBalance + (currentBalance * interestRate); 
    } 
    System.out.println ("Your final balance after 10 years is " + currentBalance); 
    return currentBalance; 
} 

}

回答

2

請試試這個

import java.text.DecimalFormat; 



public class Visitor { 


    public static void main (String[] args) { 
     compound (0.5, 1500, 1); 
    } 

    public static double compound (double interestRate, double currentBalance, int year) { 

     for (; year <= 9 ; year ++) { 

     System.out.println ("At year " + year + ", your total amount of money is "+Double.parseDouble(new DecimalFormat("#.##").format(currentBalance))); 


     currentBalance = currentBalance + (currentBalance * interestRate); 
     } 
     System.out.println ("Your final balance after 10 years is " + currentBalance); 
     return currentBalance; 
    } 
} 
+1

DecimalFormat是要走的路。如果您反覆使用相同的格式,請將DecimalFormat設置爲靜態最終值並重新使用它以提高效率。 – AWT

1

System.out.println(),顧名思義

的行爲就像先調用print(String),然後println()

使用System.out.print()並在打印當前餘額後放入換行符。

System.out.print("At year " + year + ", your total amount of money is "); 
System.out.printf("%.2f", currentBalance); 
System.out.println(); 

// or 
System.out.print("At year " + year + ", your total amount of money is "); 
System.out.printf("%.2f\n", currentBalance); 
0

System.out.printf( 「在一年%d,您的資金總量%.2f \ n」,今年,currentBalance);

0

故障呼叫是打印給定內容後追加新行的第一個System.out.println()。

有兩種解決方案 -

方法-1:

System.out.print("At year " + year + ", your total amount of money is "); 
System.out.printf("%.2f\n", currentBalance); 

方法-2:[用的println使用的String.format()()]

System.out.println ("At year " + year + ", your total amount of money is " 
             + String.format("%.2f", currentBalance)); 

兩者都將產生相同的結果。即使是第二個更具可讀性。

輸出:

在今年1,您的資金總量爲1500.00

在今年2,你的資金總量爲2250.00

在今年3,你的資金總量3375.00所屬

在今年4,你的資金總量爲5062.50

在今年5,你的資金總額爲7593.75

在今年6,你的資金總額爲11390.63

在今年7,你的資金總額爲17085.94

在今年8,你的資金總額爲25628.91

在今年9,你的資金總額爲38443.36

經過10年的最後餘額爲57665.0390625

的String.format返回formatte d字符串。 System.out中。printf還在system.out(控制檯)上打印格式化的字符串。

按照您的需求使用它們。

相關問題