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.

Be Sociable, Share!
  • Michel

    Firefox 4.0.1 Windows 7

    Hi Larry,

    you mention somewhere that one can include javascript in jQuizme; could you provide a simple example on how to include this random number generator into Jquizme to produce an addition of 2 random (2 digits) numbers in the question part, and the calculated answer in the answer section ?

    I would like to train myself to different types of mental calculations; using jQuizme seems like the appropriate tool.

    Thanks Michel.

  • Michel

    Firefox 4.0.1 Windows 7

    wow !

    More than I asked :-)

    I will adapt it a bit to my particular needs (mental math training) and will report back.

    Thank you very much.

    Regards,

    Michel

  • http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html JP @ java classpath tutorial

    Firefox 3.6.17.NETCLR3.5.30729 Windows XP

    Fantastic tip, how about writing Random Number generator in Java ?

    JP
    10 point about Heap space in Java

  • Anonymous

    Unknown Unknown

    Its really code of the month or a year too
    Very nice tip , very useful.

    Nathan

Bad Behavior has blocked 1085 access attempts in the last 7 days.

FireStats icon Powered by FireStats