home ~ socials ~ projects ~ rss

Get Random Numbers in JavaScript

February 2014

Funcations to get random Integers and Floats. Both work with negative numbers.

Integer: min >= RESULT <= max

JavaScript
function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
Output:
min: 0 ~ max: 5 ~ possible results:

0, 1, 2, 3, 4, 5

min: -5 ~ max: 0 ~ possible results:

-5, -4, -3, -2, -1, 0

Float: min >= RESULT < max

JavaScript
function randomFloat(min, max) {
  return (Math.random() * (max - min)) + min;
}
Output:
min: 0 ~ max: 5 ~ possible results:

0.0 to 4.999999.... - for example:

min: -5 ~ max: 0 ~ possible results:

-5.0 to 0.000...001
end of line

References

Share link:
https://www.alanwsmith.com/en/01/8h/xk/vy/?get-random-numbers-in-javascript