I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
Example: 323760488
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'.
000000001 a valid number?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)
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.Math.random() is 0.0123456789123, the result of this will be 012345678, as an int that is 12345678, which is only 8 digits.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.
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.
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>
Screen scrape this page:
Math.random().function rand(len){var x='';
for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
return x;
}
rand(9);
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.
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.
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));
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;
}
var number = Math.floor(Math.random() * 900000000) + 100000000
const or let to declare variables..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)
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.
<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)