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添加十进制数字问题
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
