有没有一个确定的解决方案的JavaScript浮点错误? [英] Is there a definitive solution to javascript floating-point errors?

查看:98
本文介绍了有没有一个确定的解决方案的JavaScript浮点错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写行业应用程序。我想用Javascript创建一个前端,并试图找出一个商业用户如何处理浮点错误(我从计算机科学的角度来理解他们可能不被视为错误)。我已经阅读了大量的文章,并看到了各种各样的示例,但似乎很容易意外地打破。有没有一种明确的方法来做JavaScript的十进制数学?根据道格拉斯克罗克福德,解决这个问题的唯一方法是规模你的值为整数。通过在缩放值上使用 Math.round 确保它确实是一个整数。 (DC不会谈论舍入部分,但是我发现这是必要的,例如 Math.round(1.1 * 100))做计算。当你完成数学规模回到原来的精度。请参阅 JavaScript:The Good Parts Floating Point部分。


I write line of business applications. I'd like to build a front-end end using Javascript and am trying to figure out how to deal with, for a business user, are floating point errors (I understand from a computer science perspective they might not be considered errors). I've read plenty on this and seen all kinds of rounding hacks that work on examples given but seem prone to break down unexpectedly. Is there a definitive way to do decimal math in javascript?

解决方案

According to Douglas Crockford, the only way around this problem is scale your values to integer. Make sure it really is an integer by using Math.round on the scaled value. (DC does not talk about the rounding part, but I discovered it was necessary. e.g. Math.round(1.1 *100)) Do calculation(s). When you are done with the math scale back to original precision. See JavaScript: The Good Parts "Floating Point" section.

这篇关于有没有一个确定的解决方案的JavaScript浮点错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆