我正在尝试添加两个十进制数字(参数可以是数字或在解析之前是数字的字符串)并将结果与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'));
大话西游666
米脂
相关分类