Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.floor() | 0

I have often seen this in JavaScript:

var val = (myvar / myothervar) | 0;

Which as far as I understood was one of the many shortcuts to floor a value in JavaScript (like ~~, and >> 0, etc). However, I was looking at a piece of code recently that did this:

var val = Math.floor(myvar/ myothervar)|0;

They used Math.floor() and then also did a bitwise OR with 0. The author did this many times, so it wasn't just a typo they did once. What do you gain by doing both?

For the curious, the code I am referring to can be found here

like image 815
Chad Avatar asked Apr 16 '13 20:04

Chad


People also ask

What is Math floor ()?

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

What does floor () do in Python?

floor() method rounds a number DOWN to the nearest integer, if necessary, and returns the result.

What does Math floor () do to positive numbers?

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.

What is Math floor 3.6 in Java?

The Math. floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.g towards the lesser value. Hence, math. floor(3.6) = 3.


1 Answers

You might not have thought of:

  • Math.floor(NaN) == NaN (ok, not really, but Math.floor(NaN) is NaN)
  • Math.floor(NaN) | 0 == 0

Also relevant for Infinity

As pointed out by @apsillers, this is probabably to eliminate Infinitys:

var x = 1;
console.log(Math.floor(1 / x));      // 1
console.log(Math.floor(1 / x) | 0);  // 1
x = 0;
console.log(Math.floor(1 / x));      // Infinity
console.log(Math.floor(1 / x) | 0);  // 0
like image 172
Eric Avatar answered Nov 13 '22 13:11

Eric