I was reading a JavaScript tutorial and searching for functions on MDN website when I stumbled across this example of Math.random()
:
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
While I understand that Math.floor
chooses the biggest number and with that erases all numbers that have decimal values, I already learnt another function called parseInt()
which just deletes all of the numbers after point. So, what's the difference between those two? Couldn't I just use
function getRandomInclusive(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
}
instead?
I got idea while writing this question that Math.floor()
might write 5 when it's 4,5 and parseInt()
would write 4, but it's not really important for random number generator as I understand (if you know any examples of when it would be important, please tell me!) So, there's still not much of a difference in this case?
parseInt
parses a string into an integer, reading only digits at the beginning of that string. It is not appropriate to use to round a number to an integer. The number will be converted to a string first, sometimes with unexpected results:You’re thinking of rounding to the nearest whole number, which is what
Math.round
does.Math.floor
always rounds down.The clear difference is that
Math.floor
is a function that works on numbers whileparseInt
is a function that takes a string. You don't want to use the latter here as we deal with random numbers.If you are unsure about the rounding mode, compare
Math.floor
,Math.round
andMath.ceil
.Here's an example where their behaviour differs drastically: negative numbers.
The semantic difference pointed out in other answers, however, is probably more important. Even if it does work for your particular and specific use-case, it's best to pick the one with the correct semantics. (There are countless other ways to return a seemingly random integer from a function, you should pick the one that's the least likely to make your code hard to maintain.)