jream — 2008-05-13T10:48:14-04:00 — #1
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
mrhoo — 2008-05-13T11:37:17-04:00 — #2
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.
felgall — 2008-05-13T15:44:32-04:00 — #3
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.
mrhoo — 2008-05-13T17:20:29-04:00 — #4