Languages
[Edit]
EN

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

8 points
Created by:
Marcin
15740

In JavaScript it is possible to randomize float number in range with exclusive max value in following way.

1. Custom random method example

// ONLINE-RUNNER:browser;

/*
	inclusive min (result can be equal to min value)
    exclusive 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) * Math.random();
}

// Example:

console.log(randomizeFloat()); // 1.67319916301163e+308
console.log(randomizeFloat(5)); // 2.7593705936801918
console.log(randomizeFloat(10, 80)); // 37.54521514384005
console.log(randomizeFloat(-50, 50)); // -30.632843429520975

See also

  1. JavaScript - Math.random() method example
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join