77

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

Example: 323760488

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

19 Answers19

116

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

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
ggg
  • 1,673
  • 1
  • 11
  • 5
  • How would that be 9 digits in length? 9 digits needs to be a fixed length never more or less – AnApprentice Aug 09 '10 at 03:23
  • 1
    just need to handle cases like 0.000001234, pad with zeros up to 9 digits – Mitch Wheat Aug 09 '10 at 03:24
  • @nobosh: 0 is a valid digit, even on the left side of your number. If you wanted a number >= 100000000, then you would have to say so (I've updated my answer to cover this case). – ggg Aug 09 '10 at 03:24
  • 1
    convert the resulting number to a string. Pad with zeroes on left if length < 9. Zeroes are perfectly good random numbers and should not suffer discrimination! – Larry K Aug 09 '10 at 03:27
  • @nobosh: It depends, are leading zeros allowed? For example, is `000000001` a valid number? – slebetman Aug 09 '10 at 03:27
  • `Math.floor(Math.random() * 1000000000);` could be way more elegantly written as `Math.floor(Math.random() * 1e9);` – Austin Pray Jul 29 '14 at 14:51
  • The first function is not valid, it doesn't return always a 9 digit number. – joseantgv Apr 05 '18 at 08:55
  • Doesn't work. If the random is lower 0.1 the resulting number of output digits is not guaranteed – decades Aug 28 '19 at 09:52
  • Better https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript – decades Aug 28 '19 at 09:59
  • I know the question is not about unique numbers but, can we add Date.now() to prevent duplicated numbers after some time since math.random() is pseudo-random? like `Math.floor(100000000 + Date.now() + Math.random() * 900000000)` – ajay Jan 01 '21 at 07:18
  • It could be written also as `Math.floor(Math.random() * 10 ** 9)` – Claudio Catterina Aug 23 '22 at 13:15
  • ⚠️ *BE CAREFUL* ⚠️ length could not be ALWAYS length of `12` but also `11` sometime ! The second answer is ensuring that the length will always be the same – Emidomenge Feb 06 '23 at 10:31
93

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)

mykhal
  • 19,175
  • 11
  • 72
  • 80
  • 4
    And these come out zero padded sweet – Tegra Detra Oct 09 '13 at 12:18
  • 1
    @user1167442 because `Math.random()` produces something like `0.7184519988812283`. First, convert that decimal to a string, which you can think of as an array of characters. Next, slice the character array beginning at index 2, which is right after the decimal place, and end after index 11, which will give you nine total characters: `0.[718451998]8812283`. – Jesse Bunch Oct 03 '16 at 06:40
  • 2
    This answer is light years better than the others. – dgo Oct 07 '16 at 01:34
  • that's the JavaScript way of doing things ;) BTW if you care about the type returned, wrap the expression with `parseInt(...)` in order to get a number instead of a string – ducin Jun 12 '18 at 15:04
  • 2
    Couldn’t this still potentially return a number that starts with a 0 (if the random number is < 0.1) – Ryan Aug 04 '18 at 22:46
  • 2
    @Ryan exactly. If the number returned by `Math.random()` is `0.0123456789123`, the result of this will be `012345678`, as an int that is `12345678`, which is only 8 digits. – bkis Feb 22 '19 at 14:34
  • Thank you for the answer - I'm wondering what the max length you could get from this method is? Will the Math.random() always be the exact length of your example (0.12345678901234)? – Andrew Takao May 20 '21 at 00:40
  • That's very elegant! Thank you. – jbernardo Aug 19 '22 at 12:22
  • 1
    This has a max of 17 digits. toFixed has a max of 52 digits. – SkySpiral7 Dec 09 '22 at 14:50
31

Also...

function getRandom(length) {

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

}

getRandom(9) => 234664534

José
  • 311
  • 3
  • 2
16

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.

Johnny Leung
  • 564
  • 4
  • 7
8

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.
fusion27
  • 2,396
  • 1
  • 25
  • 25
cespon
  • 5,630
  • 7
  • 33
  • 47
8
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.

nvitaterna
  • 416
  • 5
  • 12
2

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>
Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
Katie Mary
  • 82
  • 3
2

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))
bkis
  • 2,530
  • 1
  • 17
  • 31
1

Screen scrape this page:

JohnB
  • 18,046
  • 16
  • 98
  • 110
  • 2
    Screen scraping is not reliable because links die and websites change... If the link dies screen scraping won't work. If the website changes, your screen scraping might break. Also, setting up screen scraping will several times more work than writing `Math.random()`. – Tyler Jun 12 '18 at 16:50
  • Those are true points! It was meant as a joke though. Although, about 8 years after this answer was given, the link still works! – JohnB Jun 13 '18 at 17:21
  • They made an api now https://api.random.org/json-rpc/1/ , by the way, that link still works – Emeeus Aug 03 '18 at 17:34
1
function rand(len){var x='';
 for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
 return x;
}

rand(9);
  • 1
    You might add some explanatory sentences, this increases the value of your answer :-) – MBT May 06 '18 at 17:07
0

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

hythlodayr
  • 2,377
  • 15
  • 23
0

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.

Dee
  • 282
  • 1
  • 9
0

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));
Emeeus
  • 5,072
  • 2
  • 25
  • 37
0
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;
}
andreas
  • 16,357
  • 12
  • 72
  • 76
0
  1. With max exclusive: Math.floor(Math.random() * max);

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

gildniy
  • 3,528
  • 1
  • 33
  • 23
0

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.

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

For a number of 10 characters

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

From https://gist.github.com/lpf23/9762508

This answer is intended for people who are looking to generate a 10 digit number (without a country code)

0
let myNine = Math.random().toString().substring(2, 11)

Here's a breakdown of the code:

Math.random(): This function generates a random decimal number between 0 (inclusive) and 1 (exclusive). It uses the JavaScript Math object's random method.

toString(): The toString method converts the random decimal number into a string representation.

substring(2, 11): The substring method extracts a portion of the generated string. In this case, it starts at index 2 and ends at index 10 (11 is excluded), resulting in a substring of length 9 characters.

By using Math.random() and converting it to a string, we can manipulate and extract a substring to obtain a specific number of digits. The resulting myNine variable will hold a random 9-digit number as a string.

Note that the range of the generated number depends on the Math.random() function, which produces numbers between 0 and 1. The substring method is used to extract a portion of the string, but it doesn't affect the range of the generated number itself.

Philip Mutua
  • 6,016
  • 12
  • 41
  • 84
user7394313
  • 522
  • 4
  • 4