我正在尝试将两个十进制数相加(参数可以是数字或在解析之前为数字的字符串),并将结果与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'));
.toFixed()
returns a string so you'll need to convert it back to a number.let f = parseFloat(c.toFixed(1));
- zer00neresult
字符串中似乎出现了一些不可见字符。你可能需要考虑解析和使用.toFixed
对result
进行精度控制,以确保准确性。 - Hamms