Javascript 数学计算问题

发布于 2024-12-09 21:29:07 字数 126 浏览 3 评论 0原文

为什么如果我在javascript中执行此操作,我会得到以下结果:

1234.56 * 10 = 12345.599999999999

它应该是123456。我该如何解决这个问题?

谢谢。

Why is it if I do this in javascript, I get the following result:

1234.56 * 10 = 12345.599999999999

It should be 123456. How can I get around this problem?

Thanks.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

左岸枫 2024-12-16 21:29:07

浮点并不精确,因为在它们的范围内(或者更精确地说在任何范围内)有无限个数字,并且只有有限数量的位来存储该数据。

查看每个程序员都应该了解的浮点运算知识

Floating points are not exact, since there are ifinite numbers at their range [or in any range to be more exact], and only a finite number of bits to store this data.

Have a look at what every programmer should know about floating point arithmetics.

べ映画 2024-12-16 21:29:07

另一个简单的解决方案:

parseFloat((1234.56 * 10).toPrecision(12))

结果将是:12345.6,是的......它适用于十进制数字。

Another easy solution:

parseFloat((1234.56 * 10).toPrecision(12))

and the result will be: 12345.6, and YES... it works with decimal numbers.

清风挽心 2024-12-16 21:29:07

正如其他人所说,浮点等等。

简单的解决方案是做这样的事情:

var answer = parseInt(1234.56 * 10);

或者只使用 Math.round?

As the others said, floating points and so on.

Easy solution would be to do something like this:

var answer = parseInt(1234.56 * 10);

Or just use Math.round?

不回头走下去 2024-12-16 21:29:07

JS 中的所有数字都是由 float 内部定义的,并在需要时删除较低有效的数字。

(10000000000000000000000000000 + 1) == 10000000000000000000000000000
// this will return true

众所周知,JavaScript 经常在数字中丢失位。所以要小心处理

All numbers in JS are internally defined by float and drop the less significant digits if needed.

(10000000000000000000000000000 + 1) == 10000000000000000000000000000
// this will return true

And javascript is well known for droping bits quite often in numbers. So handle with care

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文