2015-09-08 84 views
2

我試過DecimalFormat和parseFloat,兩者都不行。如何將循環Javascript程序格式化爲2位小數?

var NumOfOrganisms = 2; 
    var DailyIncrease = .30; 
    var NumOfDays; 

    console.log("Day" + '\t' + "Approximate Population"); 
    console.log('1' + '\t' + NumOfOrganisms); 

    for(NumOfDays = 2; NumOfDays <= 10; NumOfDays++) { 
     NumOfOrganisms = NumOfOrganisms + (NumOfOrganisms * DailyIncrease); 
     console.log(NumOfDays + '\t' + NumOfOrganisms); 
    } 

回答

3

你必須使用的函數toFixed()爲了做到這一點,裏面,作爲一個參數指定要爲十進制數的地方量。

在這裏你去:

var NumOfOrganisms = 2; 
    var DailyIncrease = .30; 
    var NumOfDays; 

    console.log("Day" + '\t' + "Approximate Population"); 
    console.log('1' + '\t' + NumOfOrganisms); 

    for (NumOfDays = 2; NumOfDays <= 10; NumOfDays++) { 
     NumOfOrganisms = NumOfOrganisms + (NumOfOrganisms * DailyIncrease); 
     console.log(NumOfDays + '\t' + NumOfOrganisms.toFixed(2)); 
    } 
+0

哇你真棒!謝謝 – agentmg123

相關問題