在JVAScript中,我如何控制数组的输出以使数字仅使用2个小数位置



function tipCalc(bill) {
  var tipPercent;
  if (bill < 50 ) {
    tipPercent =  .20;
  } else if (bill >= 50 && bill < 200){
    tipPercent = .15;
  } else {
    tipPercent = .10;
  }
  return tipPercent * bill;
}
var bills = [124, 48, 268];
var tips = [tipCalc(bills[0]),
           tipCalc(bills[1]),
           tipCalc(bills[2])];
var finalValues =[bills[0] + tips[0],
                 bills[1] + tips[1],
                 bills[2] + tips[2]];
console.log(tips, finalValues);

我希望18.59999999999998显示为$ 18.6(在Console.log中)。我尝试使用.tofixed(2),但没有成功。

toFixed()返回 string您需要使用Number()转换回号码

function tipCalc(bill) {
var tipPercent;
  if (bill < 50 ) {
    tipPercent =  .20;
  } else if (bill >= 50 && bill < 200){
    tipPercent = .15;
  } else {
    tipPercent = .10;
  }
  return Number((tipPercent * bill).toFixed(1));
}
var bills = [124, 48, 268];
var tips = [tipCalc(bills[0]),
              tipCalc(bills[1]),
              tipCalc(bills[2])];
var finalValues =[bills[0] + tips[0],
                  bills[1] + tips[1],
                  bills[2] + tips[2]];
console.log(tips, finalValues);

.toFixed()仅适用于数字值,首先将finalValues转换为数字,然后尝试

console.log('$' number(finalValues).tofixed(2));

希望它会有所帮助。

使用 .toFixed(1)对圆形值。TOFIXED用于格式化小数右侧具有特定数字数字的数字。您可能会使用tofixed()直接返回该值。首先将.tofixed()值保存在变量中,然后返回该变量。

function tipCalc(bill) {
var tipPercent;
  if (bill < 50 ) {
    tipPercent =  .20;
  } else if (bill >= 50 && bill < 200){
    tipPercent = .15;
  } else {
    tipPercent = .10;
  }
var val=(tipPercent * bill).toFixed(1);
  return parseFloat(val);
}
  var bills = [124, 48, 268];
  var tips = ["$"+tipCalc(bills[0]),
              "$"+tipCalc(bills[1]),
              "$"+tipCalc(bills[2])];
  var finalValues =["$"+ bills[0] + tips[0],
                    "$"+bills[1] + tips[1],
                    "$"+bills[2] + tips[2]];
                  
  console.log(tips, finalValues);

最新更新