'Can we replace Math.floor by ~ and still get the same result? [closed]

I see that by replacing this line of code

Math.floor(Math.random() * 10) 

by this one:

~(Math.random() * 10

I get the same result, why is that ?



Solution 1:[1]

No, since they don´t work the same. The ~ NOT operator inverts the bits of a integer, so if you have the binary number 0101 (5 in decimal), the operator would return:

~0101 = 1010;  // ~5 = 10

But since JavaScript uses 32-bit signed integer, the result would be different:

~00000000000000000000000000000101 = 11111111111111111111111111111010  // ~5 = -6

The Math.floor() function returns the maximum integer less or equal to a number, so using the same example with number 5:

Math.floor(5) // ==> would return 5

You can see that both operators return different values. However, it is possible to simulate a Math.Floor() function using the ~ operator in float number, just multiplying * -1 the number and then substracting - 1 to the result, but I hardly don´t reccommend it as it makes the code less legigable:

const number = 5.56;

console.log(~number  * -1 - 1);    // returns 5

console.log(Math.floor(number));  // returns 5

To sum up, they are differents operator, each of them has his own funcionality.

Solution 2:[2]

The short answer is no, it's syntax, so you'll have to type something to round a float down to an int.

Either Math.floor() or parseInt().

If you wanted to shorten the typing for yourself you could create a short named function that returns the same result:

function mf(number){
  return Math.floor(number);
}

console.log(mf(Math.random() * 10));

Solution 3:[3]

Yes, you can:

parseInt(yourvalue)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Josef Halcomb
Solution 3 Lajos Arpad