Hey guys I was trying to generate a random number and looked at methods other people use and I always see Math.floor being used and wonder if their is any specific reason.
A technique multiplying by 10 and adding 1 to makeup for the rounded down:
This seems more practical:
ceil: Returns the value of a number rounded upwards to the nearest integer
floor: Returns the value of a number rounded downwards to the nearest integer
Does this matter a whole lot? Im wondering if there is a disadvantage to ceil, as I haven't found a bad roundup yet.. Sorry Im not that great with math
Random integers are often used to assign array items as values.
Math.floor(Math.random()*array.length) will return an index between 0 and the largest array index.
Math.ceil in the same expression will never return array and will occasionally return array[array.length], which is one more than the largest array item, and an error if you don't catch it.
Suit yourself, but often there is a reason one method is used instead of another.
The difference between the two versions is when the number doesn't have any decimal places in which case floor+1 will return a number 1 greater than ceil since when there are no decimals floor and ceil both round the number to itself.
This topic is now closed. New replies are no longer allowed.