在JavaScript中处理四舍五入错误的最佳实践

发布于 2025-01-31 16:16:17 字数 846 浏览 2 评论 0原文

我在JavaScript中的浮点四舍五入问题。据我所知,JavaScript中的数字是引擎盖下方的IEEE-754浮点(对此没有任何选择),因此由于舍入而言,不允许所有整数值。

例如,以下代码将产生此值作为输出 - > “ 637889210422071800”而不是“ 637889210422071841”

document.writeln(parseFloat("637889210422071841"));
document.writeln("<br>");
document.writeln(parseInt("637889210422071841",10));

问题在于,此数字(基本上是一个时钟)是在REST API响应中提供的,但是当我尝试阅读Resposne时,我会得到错误的价值(可能是由于JavaScript对象的某些隐式选择性化)。 幸运的是,我可以控制REST API,因此我可以更改时钟的编码方式。

因此,我想到的第一个选项是更改时钟格式并使其成为字符串,以便我可以从JavaScript中读取实际值(我仍然要解释它,但是至少保留了值,因此此解决方案是有点棘手,不是我的第一个选择)。 我考虑的另一个选择是减少时钟的大小,降低其敏感性,基本上不是使用“ 6378892104220718 | 41”,我将其截断为“ 6378892104220718”。我更喜欢第二种选项,但我担心可能的舍入误差不是均匀分布的事实(由于IEEE-754数字的基本实用结构,因此。

因此,我想问哪种方法是否有一种方法可以在JavaScript中处理这种情况,如果没有最佳练习,我想询问是否减少时钟版本可以解决我的问题。

i have issue with floating point rounding in javascript. As far as i know number in javascript are IEEE-754 floating point under the hood (no option about that), so not all integer value are allowed due to rounding.

For example the following code will produce this value as output -> "637889210422071800" instead of "637889210422071841" as one should expect

document.writeln(parseFloat("637889210422071841"));
document.writeln("<br>");
document.writeln(parseInt("637889210422071841",10));

Problem is that this number (basically a clock) is served in a rest api response, but when i try read the resposne i get the wrong value (probably due to some implicit deserialization over javascript object).
Luckily i have control over the rest api, so i can change how the clock is encoded.

So first option come to my mind is to change the clock format and make it a string, so that i can read the real value from javascript (i have still to interpret it, but at least the value is preserved, so this solution is a bit tricky and is not my first choiche).
Another option i think about is to decrease the size of my clock, reducing it's sensibility, basically instead of use "6378892104220718|41" i will truncate it to "6378892104220718". I prefer the second option, but i am concerned about the fact that maybe the rounding error are not uniformly distributed (due to base-exponent structure of IEEE-754 numbers).

So i would like to ask which if there is a way to handle situation like that in javascript, and if there is not a best practice, i would like to ask if reduced clock version will solve my issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文