Code of the Day: Javascript Random Number Generator

Code
*Updated*

//@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

//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.

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

View Comments

  • 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.

  • 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

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago