Skip to content

Instantly share code, notes, and snippets.

@JonathanDn
Last active May 1, 2019 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanDn/fa2d8dd90f5d767f549e3b93f0754635 to your computer and use it in GitHub Desktop.
Save JonathanDn/fa2d8dd90f5d767f549e3b93f0754635 to your computer and use it in GitHub Desktop.
Javascript - get random integers from range (float, integer, bool), random floats, random boolean(50% 50%)
/* Get a random floating point number between `min` and `max` */
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
/* Get a random integer between `min` and `max`
- Inclusive(both min and max) due to -> (max - min + 1)
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
/* Get a random boolean value - 50% 50% */
function getRandomBool() {
return Math.random() >= 0.5;
}
/* get number between 0 and 0.01 */
getMeRandomRange(min, max) {
return Math.round((Math.random() * (max - min + 1) + min) * 10) / 100;
}
/* Not Generic Yet */
/* Get three decimal limit points random in range (from -0.01 to 0.01 for example) */
/* Total Options are 20 */
/* Try look for a generic func that can accept min/max
with positive/negative values and give random between negative and positive
between two places decimal limit points.
My Motivation was to raffle a number between -0.01 and 0.01 with this limit percision point */
getThreeLimitPointsPercisionRange(0, 20) {
return ((Math.floor(Math.random() * (20 - 0 + 1) + 0)) - 10) / 1000
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment