Tuesday, January 8, 2013

JavaScript - How to get random numbers and random alpha-numeric numbers?


In this article we will see how to generate random numbers and alpha-numeric numbers in JavaScript  We will use JavaScript Math.random function to generate random numbers.

Math.random function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Please see the below function.


1. Get random numbers

//get random numbers
function getRandomNumber() {
var max = 10;
var randomnumber = Math.floor(Math.random()*max)
return randomnumber;
}

2. Get random numbers between minimum and maximum range

//get random numbers between minimum and maximum range
function getRandomNumber() {
var min = 10;
var max = 20;
var randomnumber = Math.floor((Math.random()*(max - min + 1))+min);
return randomnumber;
}



3. Get random numeric numbers of given length

//get random numeric numbers
var numbers = '0123456789';
var length = 5;

function getRandomNumbericNumbers() {
var result = '';

for (var i = length; i > 0; --i)
result += numbers[Math.round(Math.random() * (numbers.length - 1))];

return result;
}

4. Get random alpha-numeric numbers of given length

//get random alpha-numeric numbers
var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var length = 10;

function getRandomAlphaNumbericNumbers() {
var result = '';

for (var i = length; i > 0; --i)
result += characters[Math.round(Math.random() * (characters.length - 1))];

return result;
}

5. Get random alpha-numeric numbers of length between minimum and maximum range

//get random alpha numeric numbers
var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var minLength = 5;
var maxLength = 10;

function getRandomAlphaNumbericNumbers() {

var length = Math.floor((Math.random()*(maxLength - minLength + 1))+minLength);

var result = '';

for (var i = length; i > 0; --i)
result += characters[Math.round(Math.random() * (characters.length - 1))];

return result;
}

No comments:

Post a Comment