JavaScript添加十进制数问题 [英] JavaScript adding decimal numbers issue

查看:157
本文介绍了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

UPDATE

是否可以先将数字乘以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

这篇关于JavaScript添加十进制数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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