Code of the Day: Javascript Random Number Generator

Code
*Updated*

1
2
3
4
5
6
7
8
9
10
//@function: getRandomNum( i, decLen )
/**
* @param i, a number for the number range. [0, i)
* @param decLen, the number of fixed decimal length.
* @returns number that is either a float( number with decimals ) or integer (whole number).
* @note if not arguments are passed, then 0 or 1 is returned.
*/
var getRandomNum = function( i, decLen ){
	return (Math.random() * (i||1) ).toFixed(decLen);
};

Demo
http://jsbin.com/uvuze3/2/

Parameters
Todays code of the day is a random number generator coded in javascript.
getRandomNum() enhances the Math.random() function that javascript provides by offering you the ability to get a random float ( number with decimals ) or integer( whole number ) value.

Example output

1
2
3
4
5
6
//get value from Math.random()
getRandomNum();	//might return 0
//get value between [0,1) with 5 decimals
getRandomNum(1,5);	//might return 0.83034
//get value from [0,99]
getRandomNum(100);	//might return 84

Please leave a comment below.

(Page view Count: 73)