77

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

Example: 323760488

22 Answers 22

121

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

Sign up to request clarification or add additional context in comments.

12 Comments

How would that be 9 digits in length? 9 digits needs to be a fixed length never more or less
just need to handle cases like 0.000001234, pad with zeros up to 9 digits
@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).
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!
@nobosh: It depends, are leading zeros allowed? For example, is 000000001 a valid number?
|
96

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)

9 Comments

And these come out zero padded sweet
@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.
This answer is light years better than the others.
Couldn’t this still potentially return a number that starts with a 0 (if the random number is < 0.1)
@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.
|
33

Also...

function getRandom(length) {

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

}

getRandom(9) => 234664534

Comments

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.

Comments

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

3 Comments

I like it but disclaimer: may contain leading 0s which may or may not be what you want.
Math.random().toFixed has a max of 52 digits on my Chrome (the rest of the 100 are always 0).
Best answer IMO.
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.

Comments

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>

3 Comments

off to a good start (lol) left this part out which goes before the function
<!-- placeholder for where random number will go --> <h1 class="text-center" id="random-number"></h1> --> <script type="text/javascript">
The question says nothing about JQuery.
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))

Comments

1

Screen scrape this page:

3 Comments

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().
Those are true points! It was meant as a joke though. Although, about 8 years after this answer was given, the link still works!
They made an api now api.random.org/json-rpc/1 , by the way, that link still works
1
function rand(len){var x='';
 for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
 return x;
}

rand(9);

1 Comment

You might add some explanatory sentences, this increases the value of your answer :-)
1
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.

Comments

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.

Comments

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));

Comments

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;
}

Comments

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

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

Comments

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.

Comments

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

1 Comment

It's a little redundant to the top answer, isn't it? Also, please use const or let to declare variables..
0

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

Comments

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)

Comments

0
`98${Math.floor(100000000 + Math.random() * 90000000)}`

Comments

0

Math.random only gives you 16 decimal places (see precision of Math.random()), so if you want to ensure an arbitrary length random function, you could do this:

const randInt = (n) => Array.from(Array(n)).map(()=> Math.floor(Math.random()*10)).join('')
console.log(randInt(30))

Or using cypto.getRandomValues:

const randInt = (n) => window.crypto.getRandomValues(new Uint8Array(n)).map(e=> e % 10).join('')
console.log(randInt(40))

Although this will be much slower than other solutions, so only use this if you aren't calling it in a loop. You also need to call parseInt on both these functions if you don't want strings.

Comments

0
<script>
//First number has to be in the range 1-9
let randFirst =Math.floor(Math.random()*10)+1;
// get ramaining 8 as described in code above
let randRemaining=Math.random().toString().slice(2,10);
let rand=randFirst+randRemaining;
document.write(rand);
</script>

for 'n' number of digits: change to slice(2,n-2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.