Javascript Math.floor函数错误或实现之谜?

dar*_*has 8 javascript

    ?document.writeln(Math.floor(43.9));
Run Code Online (Sandbox Code Playgroud)

在浏览器中生成43.

?document.writeln(Math.floor(43.9999));???????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

生产43

 ?document.writeln(Math.floor(43.999999999999));??????????????????????????????????????? 
Run Code Online (Sandbox Code Playgroud)

再次43

然而,

    document.writeln(Math.floor(43.99999999999999));
Run Code Online (Sandbox Code Playgroud)

产生44.

小数点后9的幻数似乎是15*.

为什么是这样?

此外,Math.floor函数是否接受数字作为数字对象或数字值?

Šim*_*das 7

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


Jon*_* S. 5

双精度浮点数(也称为双精度数)能够存储非常广泛的值,但只能使用有限的精度 - 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
Run Code Online (Sandbox Code Playgroud)

您也会在其他语言中看到相同的内容.例如,PHP:

echo floor(43.99999999999999); // 43
echo floor(43.999999999999999); // 44
Run Code Online (Sandbox Code Playgroud)