Languages
[Edit]
EN

JavaScript - random float number in range with inclusive max value example

14 points
Created by:
Root-ssh
177980

In JavaScript, it is possible to randomize a float number in a range with an inclusive max value in the following way.

1. Custom random method example

// ONLINE-RUNNER:browser;

// Generates values from <0, 1>
function randomizeValue() {
	var value = (1 + 10E-16) * Math.random();
  
  	if (value > 1.0) {
    	return 1.0;
    }
  
  	return value;
}

/*
	inclusive min (result can be equal to min value)
    inclusive max (result will not be to max value)
*/
function randomizeFloat(min, max) {
  	if(max == null) {
    	max = (min == null ? Number.MAX_VALUE : min);
      	min = 0.0;
    }
  
  	if(min >= max) {
    	throw new Error("Incorrect arguments.");
    }

    return min + (max - min) * randomizeValue();
}

// Example:

console.log(randomizeFloat()); // 1.1960373039711962e+308
console.log(randomizeFloat(5)); // 0.7663988388633522
console.log(randomizeFloat(10, 80)); // 67.81113931017913
console.log(randomizeFloat(-50, 50)); // -13.713816892801674

See also

  1. JavaScript - Math.random() method example
  2. JavaScript - random float number in range with exclusive max value example

Alternative titles

  1. JavaScript - randomize float number in range with inclusive max value example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join