I have seen many places using Math.floor()
and Math.random()
like below
$(\'a.random-color\').hover(function() { //mouseove
~~Number
is only the Math.floor()
for positive numbers. For negative numbers, it is the Math.ceil()
.
For positive numbers you can use:
Math.floor(x) == ~~(x)
Math.round(x) == ~~(x + 0.5)
Math.ceil(x) == ~~(x + 1)
For negative numbers you can use:
Math.ceil(x) == ~~(x)
Math.round(x) == ~~(x - 0.5)
Math.floor(x) == ~~(x - 1)
Math.random
will give you a floating point number between 0 (inclusive) and 1 (exclusive).
Multiplying that by 256 will give you a number in the range 0 (inclusive) through 256 (exclusive), but still floating point.
Taking the floor of that number will give you an integer between 0 and 255 (both inclusive).
It's the integer from 0 to 255 that you need to construct RGB values like rgb(72,25,183)
.
It seems a random color is desired - one with each component random between 0 and 255.
Math.random() returns a random number on [0,1) (ie it may be exactly zero or up to but not including one).
Multiplying that random value by 256 gives a random number on the range [0,256) (ie it may be 255.99, but never 256). Almost there, but not quite.
Math.floor() rounds the number downwards to the nearest whole integer, making the result an integer on [0,255] as desired.
Math.random returns value between 0 and 1. You are multiplying it with 256 so it will return some float value between 0 and 256. math.floor will omit fraction value from it.
Math.floor will give a whole number and gets rid of the decimals.
Math.random returns a number between 0 and 1 and therefore will produce decimal numbers when multiplied with 256. Thats why you want to use floor to get rid of the decimals otherwise the rgb values won't work.
The Math.floor()
is to drop the decimal portion of the Number
. It is the opposite of Math.ceil()
.
You can also double the invert bitwise operator (~~
) to achieve the same as Math.floor()
(though of course the floor()
method is much more readable to most).
~~(Math.random() * 256)