Using Math.random() in JavaScript
A short guide to .ceil, .floor, and .round
Aug 28, 2018
In JavaScript, to get a random number between 0 and 1, use the Math.random()
function.
console.log(Math.random())
0.5408145050563944
If you want a random number between 1 and 10, multiply the results of Math.random
by 10, then round up or down.
Use .floor
to round down to a whole number:
console.log(Math.floor(Math.random() * 10))
Use .ceil
to round up to a whole number:
console.log(Math.ceil(Math.random() * 10))
Use .round
to round to the nearest whole number:
console.log(Math.round(Math.random() * 10))