Reputation: 110960
I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
Example: 323760488
Upvotes: 77
Views: 180190
Reputation: 54
<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)
Upvotes: 0
Reputation: 3
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.
Upvotes: 0
Reputation: 552
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.
Upvotes: 1
Reputation: 1175
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)
Upvotes: 0
Reputation: 3
var number = Math.floor(Math.random() * 900000000) + 100000000
Upvotes: 0
Reputation: 37
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.
Upvotes: 0
Reputation: 3913
With max
exclusive: Math.floor(Math.random() * max);
With max
inclusive: Math.round(Math.random() * max);
Upvotes: 0
Reputation: 1713
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'.
Upvotes: 120
Reputation: 2587
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))
Upvotes: 2
Reputation: 46
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;
}
Upvotes: 0
Reputation: 5250
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));
Upvotes: 0
Reputation: 463
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.
Upvotes: 10
Reputation: 11
function rand(len){var x='';
for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
return x;
}
rand(9);
Upvotes: 1
Reputation: 82
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>
Upvotes: 2
Reputation: 5760
In one line(ish):
var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
Steps:
1 ≤ x < 10
.Math.pow(10,len-1)
(number with a length len
).parseInt()
to remove decimals.Upvotes: 8
Reputation: 282
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.
Upvotes: 0
Reputation: 331
Also...
function getRandom(length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));
}
getRandom(9) => 234664534
Upvotes: 33
Reputation: 574
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.
Upvotes: 16
Reputation: 19905
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)
Upvotes: 95