【问题标题】:parseFloat & toFixed only returning 1 decimal pointparseFloat & toFixed 只返回 1 个小数点
【发布时间】:2020-04-30 19:57:08
【问题描述】:

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

在添加 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);

【问题讨论】:

  • 作为浮点数,1.20 没有意义,但作为字符串,你可以有 1.20。所以如果你想要两个小数点,你必须使用字符串。
  • 重要提示:如果您处理的是金钱,则不应使用主要单位(例如美元)。计算机(以 2 为基数)不能很好地代表以 10 为基数。而是做金融应用所做的事情 - 以次要单位(美分)进行交易,然后在需要显示时将它们显示为美元和美分(或其他任何形式)。

标签: javascript arrays floating-point parsefloat tofixed


【解决方案1】:

Number.prototype.toFixed() 返回 string 表示 number 你用正确的小数位数调用它,但如果你用 parseFloat 将它解析回 number,这些将消失,如 @ 987654327@ 不关心尾随零。

你可以通过去掉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);

【讨论】:

    【解决方案2】:

    Javascript 中的数字根据需要输出到控制台,小数位数尽可能多。

    console.log(1.0000001)
    console.log(1.1)

    您的所有数字仅显示一位小数,因为它们只有一位小数。如果您想以特定精度显示它们,则应该返回一个字符串。

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

    【讨论】:

      【解决方案3】:

      我将 toFixed 方法移到了您的 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(217);
      console.log(tips);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多