JavaScript adding decimal numbers issue(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添加十进制数字问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript添加十进制数字问题


基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01