Javascript Math.floor 函数失误或实现之谜
Javascript Math.floor function blunder or implementation mystery?
document.writeln(Math.floor(43.9));
在浏览器中生成 43
。document.writeln(Math.floor(43.9999));
产生 43
document.writeln(Math.floor(43.999999999999));
又是 43
然而
document.writeln(Math.floor(43.99999999999999));
产生44。
小数点后 9 的神奇数字似乎是 15*。
这是为什么呢?
此外,Math.floor 函数是否接受数字作为数字对象或数字值?
IEEE 754 双精度二进制浮点格式(这是 JavaScript 用于其数字类型的格式)为您提供 15 - 17 个有效十进制数字的精度。
这给出了 15 - 17 个有效的十进制数字精度。如果 最多 15 个有效小数的十进制字符串转换为 IEEE 754双精度,然后转换回相同的数字 的有效十进制,则最终字符串应与 源语言;如果将 IEEE 754 双精度转换为 具有至少 17 个有效小数的十进制字符串,然后转换 回到双精度,那么最终数字必须与原始数字 [1] 匹配。
来源: http://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64
双精度浮点数(又称双精度)能够存储非常广泛的值,但精度有限 - 15-17 位有效数字。如果执行以下操作,您将看到会发生什么情况:
var x = 43.99999999999999;
var y = 43.999999999999999;
document.writeln(x); // 43.99999999999999
document.writeln(y); // 44
document.writeln(Math.floor(x)); // 43
document.writeln(Math.floor(y)); // 44
您也会在其他语言中看到相同的内容。例如,PHP:
echo floor(43.99999999999999); // 43
echo floor(43.999999999999999); // 44
在 Chrome 中,如果我只是在控制台中键入 43.99999999999999999999999
,它会输出 44
,这可能是您遇到的问题。浮点数是近似值
请参阅以下解决方法:
http://jsfiddle.net/k7huV/3/
var x = 43;
for( var i = 0; i < 16; i++ ){
if( i == 0 ) x += ".";
x += "9";
}
document.writeln(x);
document.writeln(parseInt(x));
输出:43.9999999999999999 43
至 43。
您可以传递 Number 的实例以及数字文本。
Math.floor(43.99999999999999);
Math.floor(new Number(43.99999999999999));
- 如何使用动画实现纸张推车
- 客户端服务器REST API captcha实现
- 如何实现此布局
- Meteor忘记了密码的实现
- 使用Native Sockets在Android中实现WebSockets
- 在样板文件中实现Ajax
- instanceof是如何在JavaScript中实现的
- 如何正确实现Jquery多选小部件
- 实现一个建立在google.com之上的自定义搜索引擎
- 多个组件是如何实现的
- window.location使用jquery mobile实现chrome跳转
- 如何在OpenERP中实现网络摄像头
- Node.js使用Series函数(模式?)实现流控制时出现意外结果
- javascript加密实现,包括可信否认
- 如何防止Math.max()返回NaN
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 如何让程序员在javascript中实现正确的回调
- 如何使用自定义辅助对象(handler)实现嵌套的每个循环
- AngularJS智能表全局配置实现
- Javascript Math.floor 函数失误或实现之谜