DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Add A JS Function For Bounded Random Numbers

04.03.2005
| 11267 views |
  • submit to reddit
        
Math.randomMax = function(maxVal,asFloat){
	var val = Math.random()*maxVal;
	return asFloat?val:Math.round(val);
}

For a random integer between 0 and 10 (inclusive), simply:
var theNumber = Math.randomMax( 10 );

For a random float value between 0 and 10, pass a truth value to the second parameter:
var theNumber = Math.randomMax( 10, true );