我正在尝试添加两个十进制数字(参数可以是数字,也可以是在解析之前为数字的字符串),然后将结果与resultInput进行比较。问题是系统无法足够准确地表示浮点数。例如,0.1 + 0.2 = 0.30000000000000004。因此,我正在尝试使用toFixed()方法使用定点表示法格式化数字。我在运行代码时得到false。不知道我在哪里弄错了。让我知道您是否有任何想法。

    function calc(firstNumber, secondNumber, operation, resultInput) {
      let a = parseFloat(firstNumber); //Number()
      let b = parseFloat(secondNumber); //Number()
      let c;
      let d = parseFloat(resultInput);
      console.log(JSON.stringify(`value of d : ${d}`)); //"value of d : NaN"

      switch (operation) {
        case '+':
          c = a + b;
          break;
        case '-':
          c = a - b;
          break;
        case '*':
          c = a * b;
          break;
        case '/':
         if (b === 0 && 1 / b === -Infinity) {
           r = Infinity;
         } else {
           r = a / b;
         }
          break;
        default:
          console.log(`Sorry, wrong operator: ${operation}.`);
      }
      console.log(JSON.stringify(`value of c: ${c}`)); // "value of c: 0.30000000000000004"
      let f = +c.toFixed(1);
      let e = +d.toFixed(1);

      console.log(JSON.stringify(`value of f: ${f}`)); // "value of f: 0.3"
      console.log(typeof f); //number
      console.log(JSON.stringify(`value of d: ${d}`)); // "value of d: NaN"
      console.log(typeof d); //number
      console.log(JSON.stringify(`value of e: ${e}`)); // "value of e: NaN"
      console.log(typeof e); //number

      if (f !== e) return false;
      // if (!Object.is(f, e)) return false;
      return true;
    }

    console.log(calc('0.1', '0.2', '+', '0.3'));

最佳答案

我多次运行您的代码,没有问题。我刚刚发现您发布的'0.3',它具有一个特殊字符,看起来像3,但不是3。因此,当您想在JS上运行它时,将显示一个错误。因此,您的解决方案是正确的。在这里检查。

function calc(firstNumber, secondNumber, operation, resultInput) {
  let a = parseFloat(firstNumber);
  let b = parseFloat(secondNumber);
  let aux = parseFloat(resultInput);
  let r;

  switch (operation) {
    case '+':
      r = a + b;
      break;
    case '-':
      r = a - b;
      break;
    case '*':
      r = a * b;
      break;
    case '/':
      if (b !== 0) {
        r = a / b;
      } else {
        r = 0;
      }
      break;
    default:
      console.log(`Sorry, wrong operator: ${operation}.`);
  }

  return (+r.toFixed(1)) === (+aux.toFixed(1));
}

console.log(calc('0.1', '0.2', '+', '0.3'));

07-28 10:44