JavaScript添加十进制数字问题

2022-01-17 00:00:00 numbers javascript

所以我正在制作一个将两个数字(十进制数)相加的脚本,我遇到了问题.

So I am making a script that adds two numbers (decimal numbers) together, which I have encountered a problem.

http://jsfiddle.net/DerekL/esqnC/

我做了脚本,结果很不错:

I made the script, it turns out pretty good:

0.1 + 0.5  //0.6
0.2 + 0.3  //0.5

但很快我就明白了:

0.1 + 0.2  //0.30000000000000004
0.01 + 0.06  //0.06999999999999999

而且我觉得它不合适.我知道使用有限位浮点数是一个缺点,但我找不到解决这个问题的方法.

And it does not look right to me. I know it is a shortcoming of using float point with finite bits, but I can't find a way to fix that.

Math.ceil   //No
Math.floor  //No
.slice      //No

更新

是否可以先将数字乘以 1000,然后将它们相加,然后再除以 1000?

Is it possible to multiply the numbers by 1000 first, then add them then divide it by 1000?

推荐答案

使用 toFixed 将其转换为去掉一些小数位的字符串,然后再转换回数字.

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.1 + 0.2).toFixed(12) // 0.3

看起来 IE 的 toFixed 有一些奇怪的行为,所以如果你需要支持 IE,这样的东西可能会更好:

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12

相关文章