Possible Duplicate:
Generating random numbers in Javascript in a specific range?
If I input a length of say 4, I need to get back a number between 0 9999.
And I want it to be 0 padded (0004), but that may be another function.
Possible Duplicate:
Generating random numbers in Javascript in a specific range?
If I input a length of say 4, I need to get back a number between 0 9999.
And I want it to be 0 padded (0004), but that may be another function.
for(var x = 5, i = 0, y = ""; i < x; ++i, y += "9");
Math.floor(Math.random()*parseInt(y)); //random number
In the for loop, x would be your input length. You could move the definition of x outside the loop also if you needed.
You could also try this and see which one runs faster (probably the first one, fyi):
for(var x = 5, y = "", i = 0; i < x; ++i, y += Math.floor(Math.random()*9));
parseInt(y); //random number
Try this:
function getNumber(range){
var max = Math.pow(10,range);
var num = Math.Random() * max;
}
As for the zerofill
you're better off trying what Nathan suggested on his comment this
function getRandom(c){
var r = (Math.random() * Math.pow(10, c)).toFixed(0);
while(r.length != c)
r = "0" + r;
return r;
}
getRandom(3);
Since it's javascript, you may want to take advantage of its weak typing in this scenario. One particular hackerish way of doing this is to generate n numbers between 0-9 and use string concatenation.
This post seems to have the answer: JavaScript expression to generate a 5-digit number in every case and you can pad with concatenation.
EDIT: so here is my implementation of it:
function random(x){
var rand = Math.floor(Math.random() * Math.pow(10,x));
var dummy = rand;
while (dummy<Math.pow(10,x-1)){
rand = "0" + rand;
dummy = dummy*10;
}
return rand;
}
Well, here's the number part. You can probably figure out the padding part.
function makeNumber(number){
var nines = "";
var returnNumber = "";
for(var i = 0; i < number; i++)
{
nines+= "9";
}
for(var i = 0; i < number; i++)
{
var returnNumber += String(Math.Random() * parseInt(nines));
}
return returnNumber;
}
Kind of sloppy but works:
var length = 4; //<-- or get however you want
var big = "";
for (i=0; i<length; i++) {
big = big + "9";
}
var big = parseInt(big);
var random = Math.floor(Math.random() * big).toString();
var random_len = random.toString().length;
if (random_len < length) {
var random_padded = random.toString()
padding = length - random_len;
for (i=0; i<padding; i++) {
random_padded = "0" + random_padded;
}
random = random_padded
}
alert(random);