首页 > 解决方案 > parseFloat & toFixed 只返回 1 个小数点

问题描述

在下面工作时,在记录数组“提示”时,推入其中的数字似乎只有一位小数。

在添加 parseFloat 之前,它会返回 2 个小数点,但它是作为字符串返回的。添加 parseFloat 后,它现在似乎只返回一个小数点。

谢谢你。

var tips = [];
var calculateTip = function(bill) {
  switch (true) {
    case bill < 50:
      tips.push(parseFloat((bill * 0.2).toFixed(2)));
      break;
    case bill >= 50 && bill < 201:
      tips.push(parseFloat((bill * 0.15).toFixed(2)));
      break;
    default:
      tips.push(parseFloat((bill * 0.10).toFixed(2)));
  }
}
calculateTip(124);
calculateTip(48);
calculateTip(268);
console.log(tips);

标签: javascriptarraysfloating-pointparsefloattofixed

解决方案


Number.prototype.toFixed()返回一个你用正确的小数位数调用它的表示,但是如果你用它解析它string,那些会消失,因为不关心尾随零。numbernumberparseFloatnumber

您可以通过摆脱以下内容来解决此问题parseFloat

const tips = [];

function calculateTip(bill) {
  if (bill < 50)
    tips.push((bill * 0.2).toFixed(2));
  else if (bill >= 50 && bill < 201)
    tips.push((bill * 0.15).toFixed(2));
  else
    tips.push((bill * 0.10).toFixed(2));
}

calculateTip(124);
calculateTip(48);
calculateTip(268);

console.log(tips);


推荐阅读