Javascript Math.floor bug or implementation secret?

​document.writeln(Math.floor(43.9)); 

produces 43 in the browser.

 ​document.writeln(Math.floor(43.9999));​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

produces 43

  ​document.writeln(Math.floor(43.999999999999));​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

again 43

but

  document.writeln(Math.floor(43.99999999999999)); 

produces 44.

The magic number 9 after the decimal point seems to be equal to 15 *.

Why is this?

Also, does the Math.floor function accept a number as a numeric object or a numeric value?

+8
javascript
source share
5 answers

The IEEE 754 double-precision binary floating-point format (which uses JavaScript for its type of number) gives you an accuracy of 15 to 17 significant decimal digits.

This gives 15 to 17 significant decimal digits. If a decimal string containing no more than 15 significant decimal places is converted to IEEE 754 double precision and then converted back to the same number from a significant decimal, then the final string must match the original; and if the double precision of IEEE 754 is converted to a decimal string with at least 17 significant decimal places, and then converted back to double, then the final number must match the original [1].

Source: http://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64

+7
source share

Double-precision floating-point numbers (bpm) can store a very wide range of values, but only with limited accuracy - 15-17 significant digits. If you do the following, you will see what happens:

 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 

You will see the same in other languages. For example, PHP:

 echo floor(43.99999999999999); // 43 echo floor(43.999999999999999); // 44 
+5
source share

In Chrome, if I just 43.99999999999999999999999 in the console, it will output 44 , it is possible that you are working. Floating points are approximations

+2
source share

See this workaround:

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)); 

Output: 43.9999999999999999 43

Correctly floors 43.999999999999999-94.

+1
source share

You can pass both an instance of Number and a numeric literal.

 Math.floor(43.99999999999999); Math.floor(new Number(43.99999999999999)); 
+1
source share

All Articles