agentmg123
agentmg123

Reputation: 159

How to format a for loop Javascript program to 2 decimal places?

I tried the DecimalFormat and the parseFloat, both won't work.

    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);
    }

Upvotes: 2

Views: 509

Answers (1)

EugenSunic
EugenSunic

Reputation: 13703

You have to use the function toFixed() in order to accomplish this, inside, as an argument you specify the amount of places you want for the decimal number.

Here you go:

  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));
  }

Upvotes: 3

Related Questions