gpt4 book ai didi

javascript - 在 JavaScript 中添加和比较两个十进制数

转载 作者:行者123 更新时间:2023-11-29 10:01:29 26 4
gpt4 key购买 nike

我正在尝试将两个十进制数相加(参数可以是数字,也可以是解析前的数字字符串)并将结果与​​ resultInput 进行比较。问题在于系统不能足够准确地表示 float 。例如,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'));

最佳答案

您可以创建一个函数来测试两个数字是否足够接近以至于可以称为相等,而不是在字符串之间来回转换。您决定了一些小的增量,如果数字至少接近那么大,您就认为它很好。

function almost(a, b, delta = 0.000001){
return Math.abs(a - b) < delta
}

// not really equal
console.log("equal?", 0.2 + 0.1 === 0.3)

// but good enough
console.log("close enough?", almost(0.2 + 0.1, 0.3))

关于javascript - 在 JavaScript 中添加和比较两个十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56178084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com