gpt4 book ai didi

javascript - JavaScript 表达式求解器

转载 作者:行者123 更新时间:2023-11-28 09:36:18 25 4
gpt4 key购买 nike

Possible Duplicate:
Elegant workaround for JavaScript floating point number problem

由于 Javascript 使用 1985 年的 IEEE 754 标准,因此无法可靠地进行 float 学,我需要一个解决方法。基本上,我需要的是一种计算 5+3*(2+8/6) 等表达式的方法。我正在考虑用字符串来实现这一点,并滚动我自己的函数来进行基本操作(+-*/%),但我首先想知道您是否知道任何库已经做到了这一点。

最佳答案

这取决于数字有多大。对于较小的数字(例如少于 14 个有效数字),四舍五入到可接受的精度可能会完成这项工作。例如给出你的例子:

var n = 0.5 / 5 + 1 / 5;  // 0.30000000000000004

var p = Math.pow(10, 14); // where 14 is calculated based on the first
// significant digit and its relationship to
// the decimal place

n = Math.round(n * p) / p; // 0.3

计算 10 的幂应该不那么难。如果数量很大,那么生活会更加困难(请参阅现有的库)。

关于javascript - JavaScript 表达式求解器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13005790/

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