I have seen many places using Math.floor()
and Math.random()
like below
$('a.random-color').hover(function() { //mouseover
var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
$(this).animate({
'color': col,
'paddingLeft': '20px'
},1000);
},function() { //mouseout
$(this).animate({
'color': original,
'paddingLeft': '0'
},500);
});
});
Why used Math.floor()
and Math.random()
?
floor() method rounds a number DOWN to the nearest integer.
random will not return 1.0 itself, multiplying what Math. random returns with 100 will result in a max value of 99.999.... and when cast to an int turns to 99. Since the randomly generated number is supposed to include 100 you'll have to multiply with 101. Multiplying with 100 will result in a max int value of 99.
To create a random decimal number between two values (range), you can use the following formula: Math. random()*(b-a)+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.
random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. . When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java. util.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With