0

So I ran across a small piece of code that looks like this Math.random() * 5 | 0 and was confused by what it did.

after some inspecting, it seems like the comparison turns the decimal into an integer. is that right? and so the piece of code is another way is saying give me a random number between 0 and 4. Can anyone explain why that is?

Mundo Calderon
  • 183
  • 2
  • 10

1 Answers1

2

1) Math.random() function always return decimal value and will be less than one. Ex - 0.2131313

random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

2) Math.random()*5 will always be less than 5. (maxvalue - 4.99999).

3) The bitwise operator '|' will truncate the decimal values.

Edit : Paul is correct. '|' does more than just truncate. But in this case Math.random()*5|0 - It truncates the decimal and returns the integar.

shan
  • 288
  • 4
  • 11
  • 1
    `|` works with _Int32_ so it will cast to _Int32_, If your number `n` is larger than `0x80000000` you'll find it does more than simply "truncating", but instead overflows into negatives, and larger than `0xFFFFFFFF` will become positive again, etc. ***fixed comment – Paul S. Nov 08 '15 at 03:02