JavaScript, Generate a Random Number that is 9 numbers in length

Javascript

Javascript Problem Overview


I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:

Example: 323760488

Javascript Solutions


Solution 1 - Javascript

You could generate 9 random digits and concatenate them all together.

Or, you could call random() and multiply the result by 1000000000:

Math.floor(Math.random() * 1000000000);

Since Math.random() generates a random double precision number between 0 and 1, you will have enough digits of precision to still have randomness in your least significant place.

If you want to ensure that your number starts with a nonzero digit, try:

Math.floor(100000000 + Math.random() * 900000000);

Or pad with zeros:

function LeftPadWithZeros(number, length)
{
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;
}

Or pad using this inline 'trick'.

Solution 2 - Javascript

why don't just extract digits from the Math.random() string representation?

Math.random().toString().slice(2,11);
/*
Math.random()                         ->  0.12345678901234
             .toString()              -> "0.12345678901234"
                        .slice(2,11)  ->   "123456789"
 */

(requirement is that every javascript implementation Math.random()'s precision is at least 9 decimal places)

Solution 3 - Javascript

Also...

function getRandom(length) {

return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));

}

getRandom(9) => 234664534

Solution 4 - Javascript

Three methods I've found in order of efficiency: (Test machine running Firefox 7.0 Win XP)

parseInt(Math.random()*1000000000, 10)

1 million iterations: ~626ms. By far the fastest - parseInt is a native function vs calling the Math library again. NOTE: See below.

Math.floor(Math.random()*1000000000)

1 million iterations: ~1005ms. Two function calls.

String(Math.random()).substring(2,11)

1 million iterations: ~2997ms. Three function calls.

And also...

parseInt(Math.random()*1000000000)

1 million iterations: ~362ms. NOTE: parseInt is usually noted as unsafe to use without radix parameter. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt or google "JavaScript: The Good Parts". However, it seems the parameter passed to parseInt will never begin with '0' or '0x' since the input is first multiplied by 1000000000. YMMV.

Solution 5 - Javascript

In one line(ish):

var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);

Steps:

  • We generate a random number that fulfil 1 ≤ x < 10.
  • Then, we multiply by Math.pow(10,len-1) (number with a length len).
  • Finally, parseInt() to remove decimals.

Solution 6 - Javascript

Math.random().toFixed(length).split('.')[1]

Using toFixed alows you to set the length longer than the default (seems to generate 15-16 digits after the decimal. ToFixed will let you get more digits if you need them.

Solution 7 - Javascript

Thought I would take a stab at your question. When I ran the following code it worked for me.

<script type="text/javascript">

    function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
    } //The maximum is exclusive and the minimum is inclusive
    $(document).ready(function() {

    $("#random-button").on("click", function() {
    var randomNumber = getRandomInt(100000000, 999999999);
    $("#random-number").html(randomNumber);
    });
    
</script>

Solution 8 - Javascript

Screen scrape this page:

Solution 9 - Javascript

function rand(len){var x='';
 for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
 return x;
}

rand(9);

Solution 10 - Javascript

Does this already have enough answers?
I guess not. So, this should reliably provide a number with 9 digits, even if Math.random() decides to return something like 0.000235436:

Math.floor((Math.random() + Math.floor(Math.random()*9)+1) * Math.pow(10, 8))

Solution 11 - Javascript


var number = Math.floor(Math.random()*899999999 + 100000000)

Solution 12 - Javascript

If you mean to generate random telephone number, then they usually are forbidden to start with zero. That is why you should combine few methods:

Math.floor(Math.random()*8+1)+Math.random().toString().slice(2,10);

this will generate random in between 100 000 000 to 999 999 999

With other methods I had a little trouble to get reliable results as leading zeroes was somehow a problem.

Solution 13 - Javascript

I know the answer is old, but I want to share this way to generate integers or float numbers from 0 to n. Note that the position of the point (float case) is random between the boundaries. The number is an string because the limitation of the MAX_SAFE_INTEGER that is now 9007199254740991

Math.hRandom = function(positions, float = false) {

  var number = "";
  var point = -1;

  if (float) point = Math.floor(Math.random() * positions) + 1;

  for (let i = 0; i < positions; i++) {
    if (i == point) number += ".";
    number += Math.floor(Math.random() * 10);
  }

  return number;

}
//integer random number 9 numbers 
console.log(Math.hRandom(9));

//float random number from 0 to 9e1000 with 1000 numbers.
console.log(Math.hRandom(1000, true));

Solution 14 - Javascript

function randomCod(){

    let code = "";
    let chars = 'abcdefghijlmnopqrstuvxwz'; 
    let numbers = '0123456789';
    let specialCaracter = '/{}$%&@*/()!-=?<>';
    for(let i = 4; i > 1; i--){

        let random = Math.floor(Math.random() * 99999).toString();
        code += specialCaracter[random.substring(i, i-1)] + ((parseInt(random.substring(i, i-1)) % 2 == 0) ? (chars[random.substring(i, i-1)].toUpperCase()) : (chars[random.substring(i, i+1)])) + (numbers[random.substring(i, i-1)]);
    }

    code = (code.indexOf("undefined") > -1 || code.indexOf("NaN") > -1) ? randomCod() : code;


    return code;
}

Solution 15 - Javascript

  1. With max exclusive: Math.floor(Math.random() * max);

  2. With max inclusive: Math.round(Math.random() * max);

Solution 16 - Javascript

To generate a number string with length n, thanks to @nvitaterna, I came up with this:

1 + Math.floor(Math.random() * 9) + Math.random().toFixed(n - 1).split('.')[1]

It prevents first digit to be zero. It can generate string with length ~ 50 each time you call it.

Solution 17 - Javascript

var number = Math.floor(Math.random() * 900000000) + 100000000

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnApprenticeView Question on Stackoverflow
Solution 1 - JavascriptgggView Answer on Stackoverflow
Solution 2 - JavascriptmykhalView Answer on Stackoverflow
Solution 3 - JavascriptJoséView Answer on Stackoverflow
Solution 4 - JavascriptJohnny LeungView Answer on Stackoverflow
Solution 5 - JavascriptcesponView Answer on Stackoverflow
Solution 6 - JavascriptnvitaternaView Answer on Stackoverflow
Solution 7 - JavascriptKatie MaryView Answer on Stackoverflow
Solution 8 - JavascriptJohnBView Answer on Stackoverflow
Solution 9 - JavascriptPrenticeRealtyView Answer on Stackoverflow
Solution 10 - JavascriptbkisView Answer on Stackoverflow
Solution 11 - JavascripthythlodayrView Answer on Stackoverflow
Solution 12 - JavascriptDeeView Answer on Stackoverflow
Solution 13 - JavascriptEmeeusView Answer on Stackoverflow
Solution 14 - JavascriptLívia NascimentoView Answer on Stackoverflow
Solution 15 - JavascriptgildniyView Answer on Stackoverflow
Solution 16 - JavascriptMasoud ShariatiView Answer on Stackoverflow
Solution 17 - Javascriptuser18510472View Answer on Stackoverflow