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

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

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

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