Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Math.floor function blunder or implementation mystery?

Tags:

javascript

    ​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

However,

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

produces 44.

The magic number of 9's after the decimal point seems to be 15*.

Why is this?

Furthermore, Does the Math.floor function accept the number as a number object, or a number value?

like image 952
darethas Avatar asked Aug 14 '12 18:08

darethas


People also ask

What does Math floor () do in JavaScript?

The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.

What is the difference between Math Trunc () and Math floor () in JavaScript?

trunc rounds down a number to an integer towards 0 while Math. floor rounds down a number to an integer towards -Infinity . As illustrated with the following number line, the direction will be the same for a positive number while for a negative number, the directions will be the opposite.

Does Math floor round down?

The FLOOR. MATH function rounds a number down to the nearest integer or a multiple of specified significance, with negative numbers rounding toward or away from zero depending on the mode.

Is Math floor slow?

The primary reason Math. floor is slower (where it actually is--in some tests I've done it's faster) is that it involves a function call.


1 Answers

The IEEE 754 double-precision binary floating-point format (which is what JavaScript uses for its Number type) gives you a precision of 15 - 17 significant decimal digits.

This gives from 15 - 17 significant decimal digits precision. If a decimal string with at most 15 significant decimal is converted to IEEE 754 double precision and then converted back to the same number of significant decimal, then the final string should match the original; and if an IEEE 754 double precision is converted to a decimal string with at least 17 significant decimal 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

like image 81
Šime Vidas Avatar answered Nov 15 '22 22:11

Šime Vidas