Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

0.1+0.2为什么不等于0.3 #45

Open
nmsn opened this issue May 9, 2023 · 1 comment
Open

0.1+0.2为什么不等于0.3 #45

nmsn opened this issue May 9, 2023 · 1 comment

Comments

@nmsn
Copy link
Contributor

nmsn commented May 9, 2023

  • 原因
  • 解决办法
@nmsn nmsn added the Javascript label May 9, 2023
@nmsn
Copy link
Contributor Author

nmsn commented May 9, 2023

原因

在 JavaScript 中,数字是以 IEEE 754 标准的二进制双精度浮点数(双精度浮点数由一位符号位、11位指数、52位小数位组成)表示的,它采用二进制的形式来表示实数。而二进制无法精确地表示某些十进制小数,例如 0.1 和 0.2,因为它们在二进制下是无限循环的小数,而浮点数只有 64 位的精度。

因此,当在 JavaScript 中执行 0.1 + 0.2 的计算时,由于无法精确表示这两个数字,它们会被转换成最接近的可表示二进制数,然后再进行计算。这会导致一个微小的舍入误差,使得结果不等于 0.3。

解决办法

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant