我试图添加两个十进制数字(参数可以是数字或字符串,它们在解析之前是数字)并将结果与数据进行比较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) {
c = a / b;
} else {
c = 0;
}
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'));
潇潇雨雨
蝴蝶刀刀
相关分类