Over a million developers have joined DZone.

Add A JS Function For Bounded Random Numbers

·
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 );
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}