如何将for循环Javascript程序格式化为小数点后2位



我尝试了DecimalFormat和parseFloat,两者都不起作用。

    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()来完成此操作,在内部,作为参数指定您想要的十进制数的位数。

给你:

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

相关内容

  • 没有找到相关文章

最新更新