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

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

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)

Also...
function getRandom(length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));
}
getRandom(9) => 234664534

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.

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.

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>

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

Screen scrape this page:
9 random numbers

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

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

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

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.

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

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

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)

Related

In JavaScript, is there a way to make 0.84729347293923 into an integer without using any string or regex manipulation?

Given any number between 0 and 1, such as 0.84729347293923, is there a simple way to make it into 84729347293923 without string or regex manipulation? I can think of using a loop, which probably is no worse than using a string because it is O(n) with n being the number of digits. But is there a better way?
function getRandom() {
let r = Math.random();
while (Math.floor(r) !== r) r *= 10;
return r;
}
for (let i = 0; i < 10; i++)
console.log(getRandom());
Integers mod 1 = 0, non integers mod 1 != 0.
while ((r*=10) % 1);
Ok, just want to refactor my code (i realized that was bad so this is what i discovered to correctly get the value as you requested).
NOTE: As the question says that "given any number between 0 and 1", this solution only works for values between 0 and 1:
window.onload = ()=>{
function getLen(num){
let currentNumb = num;
let integratedArray = [];
let realLen = 0;
/*While the number is not an integer, we will multiply the copy of the original
*value by ten, and when the loop detects that the number is already an integer
*the while simply breaks, in this process we are storing each transformations
*of the number in an array called integratedArray*/
while(!(Number.isInteger(currentNumb))){
currentNumb *= 10;
integratedArray.push(currentNumb);
}
/*We iterate over the array and compare each value of the array with an operation
*in which the resultant value should be exactly the same as the actual item of the
*array, in the case that both are equal we assign the var realLen to i, and
*in case that the values were not the same, we simply breaks the loop, if the
*values are not the same, this indicates that we found the "trash numbers", so
*we simply skip them.*/
for(let i = 0; i < integratedArray.length; i++){
if(Math.floor(integratedArray[i]) === Math.floor(num * Math.pow(10, i + 1))){
realLen = i;
}else{
break;
}
}
return realLen;
}
//Get the float value of a number between 0 and 1 as an integer.
function getShiftedNumber(num){
//First we need the length to get the float part of the number as an integer
const len = getLen(num);
/*Once we have the length of the number we simply multiply the number by
*(10) ^ numberLength, this eliminates the comma (,), or point (.), and
*automatically transforms the number to an integer in this case a large integer*/
return num * (Math.pow(10, len));
}
console.log(getShiftedNumber(0.84729347293923));
}
So the explanation is the next:
Because we want to convert this number without using any string, regex or any another thing, first we need to get the length of the number, this is a bit hard to do without using string conversions... so i did the function getLen for this purpose.
In the function getLen, we have 3 variables:
currentNumb: This var is a copy of the original value (the original number), this value help us to found the length of the number and we can do some transforms to this value whitout changing the original reference of the number.
We need to multiply this value any times is needed to transform the number to an integer and then multiplyng this value by ten to ten.
with the help of a while (this method makes the number a false integer).
NOTE: I saw "False integer" because when i was making the tests i realized that in the number is being adding more digits than normal... (Very very strange), so this stupid but important thing makes neccesary the filter of these "trash numbers", so later we proccess them.
integratedArray: This array stores the values of the result of the first while operations, so the last number stored in this array is an integer, but this number is one of the "fake integers", so with this array we need to iterate later to compare what of those stored values are different to the original value multiplied by (10 * i + 1), so here is the hint:
In this case the first 12 values of this array are exactly the same with the operation of Math.floor(num * Math.pow(10, i + 1))), but in the 13th value of the array these values are not the same so... yes!, there are those "trash numbers" that we were searching for.
realLen: This is the variable where we will store the real length of the number converting the float part of this number in an integer.
Some binary search approach:
Its useless if avarage length < 8;
It contains floating point issues.
But hey it is O(log n) with tons of wasted side computations - i guess if one counts them its event worse than just plain multiplication.
I prefer #chiliNUT answer. One line stamp.
function floatToIntBinarySearch(number){
const max_safe_int_length = 16;
const powers = [
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000
]
let currentLength = 16
let step = 16
let _number = number * powers[currentLength]
while(_number % 1 != 0 || (_number % 10 | 0) == 0){
step /= 2
if( (_number % 10 | 0) == 0 && !(_number % 1 != 0)){
currentLength = currentLength - step;
} else {
currentLength = step + currentLength;
}
if(currentLength < 1 || currentLength > max_safe_int_length * 2) throw Error("length is weird: " + currentLength)
_number = number * powers[currentLength]
console.log(currentLength, _number)
if(Number.isNaN(_number)) throw Error("isNaN: " + ((number + "").length - 2) + " maybe greater than 16?")
}
return number * powers[currentLength]
}
let randomPower = 10 ** (Math.random() * 10 | 0)
let test = (Math.random() * randomPower | 0) / randomPower
console.log(test)
console.log(floatToIntBinarySearch(test))

Javascript random number between two digits [duplicate]

Is there a way to generate a random number in a specified range with JavaScript ?
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
const rndInt = randomIntFromInterval(1, 6)
console.log(rndInt)
What it does "extra" is it allows random intervals that do not start with 1.
So you can get a random number from 10 to 15 for example. Flexibility.
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.
If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
Where:
1 is the start number
6 is the number of possible results (1 + start (6) - end (1))
Math.random()
Returns an integer random number between min (included) and max (included):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Or any random number between min (included) and max (not included):
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful examples (integers):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random
numbers. Do not use them for anything related to security. Use the Web
Crypto API instead, and more precisely the
window.crypto.getRandomValues() method.
Other solutions:
(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1
Try online
TL;DR
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max - min + 1))
}
To get the random number
generateRandomInteger(-20, 20);
EXPLANATION BELOW
integer - A number which is not a fraction; a whole number
We need to get a random number , say X between min and max.
X, min and max are all integers
i.e
min <= X <= max
If we subtract min from the equation, this is equivalent to
0 <= (X - min) <= (max - min)
Now, lets multiply this with a random number r
which is
0 <= (X - min) * r <= (max - min) * r
Now, lets add back min to the equation
min <= min + (X - min) * r <= min + (max - min) * r
For, any given X, the above equation satisfies only when r has range of [0,1] For any other values of r the above equation is unsatisfied.
Learn more about ranges [x,y] or (x,y) here
Our next step is to find a function which always results in a value which has a range of [0,1]
Now, the range of r i.e [0,1] is very similar to Math.random() function in Javascript. Isn't it?
The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1); that is, from 0 (inclusive) up to but not
including 1 (exclusive)
Random Function using Math.random() 0 <= r < 1
Notice that in Math.random() left bound is inclusive and the right bound is exclusive. This means min + (max - min) * r will evaluate to having a range from [min, max)
To include our right bound i.e [min,max] we increase the right bound by 1 and floor the result.
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max - min + 1))
}
To get the random number
generateRandomInteger(-20, 20);
Or, in Underscore
_.random(min, max)
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
jsfiddle: https://jsfiddle.net/cyGwf/477/
Random Integer: to get a random integer between min and max, use the following code
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Random Floating Point Number: to get a random floating point number between min and max, use the following code
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
E.g
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.
Get a random integer between 0 and 400
let rand = Math.round(Math.random() * 400)
document.write(rand)
Get a random integer between 200 and 1500
let range = {min: 200, max: 1500}
let delta = range.max - range.min
const rand = Math.round(range.min + Math.random() * delta)
document.write(rand)
Using functions
function randBetween(min, max){
let delta = max - min
return Math.round(min + Math.random() * delta)
}
document.write(randBetween(10, 15));
// JavaScript ES6 arrow function
const randBetween = (min, max) => {
let delta = max - min
return Math.round(min + Math.random() * delta)
}
document.write(randBetween(10, 20))
I wrote more flexible function which can give you random number but not only integer.
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(max-min+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
Fixed version.
ES6 / Arrow functions version based on Francis' code (i.e. the top answer):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
Example
Return a random number between 1 and 10:
Math.floor((Math.random() * 10) + 1);
The result could be:
3
Try yourself: here
--
or using lodash / undescore:
_.random(min, max)
Docs:
- lodash
- undescore
The top rated solution is not mathematically correct as same as comments under it -> Math.floor(Math.random() * 6) + 1.
Task: generate random number between 1 and 6.
Math.random() returns floating point number between 0 and 1 (like 0.344717274374 or 0.99341293123 for example), which we will use as a percentage, so Math.floor(Math.random() * 6) + 1 returns some percentage of 6 (max: 5, min: 0) and adds 1. The author got lucky that lower bound was 1., because percentage floor will "maximumly" return 5 which is less than 6 by 1, and that 1 will be added by lower bound 1.
The problems occurs when lower bound is greater than 1. For instance,
Task: generate random between 2 and 6.
(following author's logic)
Math.floor(Math.random() * 6) + 2, it is obviously seen that if we get 5 here -> Math.random() * 6 and then add 2, the outcome will be 7 which goes beyond the desired boundary of 6.
Another example,
Task: generate random between 10 and 12.
(following author's logic)
Math.floor(Math.random() * 12) + 10, (sorry for repeating) it is obvious that we are getting 0%-99% percent of number "12", which will go way beyond desired boundary of 12.
So, the correct logic is to take the difference between lower bound and upper bound add 1, and only then floor it (to substract 1, because Math.random() returns 0 - 0.99, so no way to get full upper bound, thats why we adding 1 to upper bound to get maximumly 99% of (upper bound + 1) and then we floor it to get rid of excess). Once we got the floored percentage of (difference + 1), we can add lower boundary to get the desired randomed number between 2 numbers.
The logic formula for that will be: Math.floor(Math.random() * ((up_boundary - low_boundary) + 1)) + 10.
P.s.: Even comments under the top-rated answer were incorrect, since people forgot to add 1 to the difference, meaning that they will never get the up boundary (yes it might be a case if they dont want to get it at all, but the requirenment was to include the upper boundary).
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.
CODE:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
Math.random() is fast and suitable for many purposes, but it's not appropriate if you need cryptographically-secure values (it's not secure), or if you need integers from a completely uniform unbiased distribution (the multiplication approach used in others answers produces certain values slightly more often than others).
In such cases, we can use crypto.getRandomValues() to generate secure integers, and reject any generated values that we can't map uniformly into the target range. This will be slower, but it shouldn't be significant unless you're generating extremely large numbers of values.
To clarify the biased distribution concern, consider the case where we want to generate a value between 1 and 5, but we have a random number generator that produces values between 1 and 16 (a 4-bit value). We want to have the same number of generated values mapping to each output value, but 16 does not evenly divide by 5: it leaves a remainder of 1. So we need to reject 1 of the possible generated values, and only continue when we get one of the 15 lesser values that can be uniformly mapped into our target range. Our behaviour could look like this pseudocode:
Generate a 4-bit integer in the range 1-16.
If we generated 1, 6, or 11 then output 1.
If we generated 2, 7, or 12 then output 2.
If we generated 3, 8, or 13 then output 3.
If we generated 4, 9, or 14 then output 4.
If we generated 5, 10, or 15 then output 5.
If we generated 16 then reject it and try again.
The following code uses similar logic, but generates a 32-bit integer instead, because that's the largest common integer size that can be represented by JavaScript's standard number type. (This could be modified to use BigInts if you need a larger range.) Regardless of the chosen range, the fraction of generated values that are rejected will always be less than 0.5, so the expected number of rejections will always be less than 1.0 and usually close to 0.0; you don't need to worry about it looping forever.
const randomInteger = (min, max) => {
const range = max - min;
const maxGeneratedValue = 0xFFFFFFFF;
const possibleResultValues = range + 1;
const possibleGeneratedValues = maxGeneratedValue + 1;
const remainder = possibleGeneratedValues % possibleResultValues;
const maxUnbiased = maxGeneratedValue - remainder;
if (!Number.isInteger(min) || !Number.isInteger(max) ||
max > Number.MAX_SAFE_INTEGER || min < Number.MIN_SAFE_INTEGER) {
throw new Error('Arguments must be safe integers.');
} else if (range > maxGeneratedValue) {
throw new Error(`Range of ${range} (from ${min} to ${max}) > ${maxGeneratedValue}.`);
} else if (max < min) {
throw new Error(`max (${max}) must be >= min (${min}).`);
} else if (min === max) {
return min;
}
let generated;
do {
generated = crypto.getRandomValues(new Uint32Array(1))[0];
} while (generated > maxUnbiased);
return min + (generated % possibleResultValues);
};
console.log(randomInteger(-8, 8)); // -2
console.log(randomInteger(0, 0)); // 0
console.log(randomInteger(0, 0xFFFFFFFF)); // 944450079
console.log(randomInteger(-1, 0xFFFFFFFF));
// Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(12).fill().map(n => randomInteger(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9]
to return 1-6 like a dice basically,
return Math.round(Math.random() * 5 + 1);
Adding float with fixed precision version based on the int version in #Francisc's answer:
function randomFloatFromInterval (min, max, fractionDigits) {
const fractionMultiplier = Math.pow(10, fractionDigits)
return Math.round(
(Math.random() * (max - min) + min) * fractionMultiplier,
) / fractionMultiplier
}
so:
randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
and for int answer
randomFloatFromInterval(1,3,0) // => 1, 2, 3
Crypto-strong random integer number in range [a,b] (assumption: a < b )
let rand= (a,b)=> a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
console.log( rand(1,6) );
This function can generate a random integer number between (and including) min and max numbers:
function randomNumber(min, max) {
if (min > max) {
let temp = max;
max = min;
min = temp;
}
if (min <= 0) {
return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
} else {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
Example:
randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4
Using random function, which can be reused.
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
This should work:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
If the starting number is 1, as in your example (1-6), you can use Math.ceil() method instead of Math.floor().
Math.ceil(Math.random() * 6)
instead of
Math.floor(Math.random() * 6) + 1
Let's not forget other useful Math methods.
This is about nine years late, but randojs.com makes this a simple one-liner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
Try using:
function random(min, max) {
return Math.round((Math.random() *( Math.abs(max - min))) + min);
}
console.log(random(1, 6));
Short Answer: It's achievable using a simple array.
you can alternate within array elements.
This solution works even if your values are not consecutive. Values don't even have to be a number.
let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];
This simple function is handy and works in ANY cases (fully tested).
Also, the distribution of the results has been fully tested and is 100% correct.
function randomInteger(pMin = 1, pMax = 1_000_000_000)
//Author: Axel Gauffre.
//Here: https://stackoverflow.com/a/74636954/5171000
//Inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
//
//This function RETURNS A RANDOM INTEGER between pMin (INCLUDED) and pMax (INCLUDED).
// - pMin and pMax should be integers.
// - HOWEVER, if pMin and/or pMax are FLOATS, they will be ROUNDED to the NEAREST integer.
// - NEGATIVE values ARE supported.
// - The ORDER of the 2 arguments has NO consequence: If pMin > pMax, then pMin and pMax will simply be SWAPPED.
// - If pMin is omitted, it will DEFAULT TO 1.
// - If pMax is omitted, it will DEFAULT TO 1 BILLION.
//
//This function works in ANY cases (fully tested).
//Also, the distribution of the results has been fully tested and is 100% correct.
{
pMin = Math.round(pMin);
pMax = Math.round(pMax);
if (pMax < pMin) { let t = pMin; pMin = pMax; pMax = t;}
return Math.floor(Math.random() * (pMax+1 - pMin) + pMin);
}
I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
This works for me and produces values like Python's random.randint standard library function:
function randint(min, max) {
return Math.round((Math.random() * Math.abs(max - min)) + min);
}
console.log("Random integer: " + randint(-5, 5));

How to Generate a random number of fixed length using JavaScript?

I'm trying to generate a random number that must have a fixed length of exactly 6 digits.
I don't know if JavaScript has given below would ever create a number less than 6 digits?
Math.floor((Math.random()*1000000)+1);
I found this question and answer on StackOverflow here. But, it's unclear.
EDIT: I ran the above code a bunch of times, and Yes, it frequently creates numbers less than 6 digits. Is there a quick/fast way to make sure it's always exactly 6 digits?
console.log(Math.floor(100000 + Math.random() * 900000));
Will always create a number of 6 digits and it ensures the first digit will never be 0. The code in your question will create a number of less than 6 digits.
Only fully reliable answer that offers full randomness, without loss. The other ones prior to this answer all looses out depending on how many characters you want. The more you want, the more they lose randomness.
They achieve it by limiting the amount of numbers possible preceding the fixed length.
So for instance, a random number of fixed length 2 would be 10 - 99. For 3, 100 - 999. For 4, 1000 - 9999. For 5 10000 - 99999 and so on. As can be seen by the pattern, it suggests 10% loss of randomness because numbers prior to that are not possible. Why?
For really large numbers ( 18, 24, 48 ) 10% is still a lot of numbers to loose out on.
function generate(n) {
var add = 1, max = 12 - add; // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.
if ( n > max ) {
return generate(max) + generate(n - max);
}
max = Math.pow(10, n+add);
var min = max/10; // Math.pow(10, n) basically
var number = Math.floor( Math.random() * (max - min + 1) ) + min;
return ("" + number).substring(add);
}
The generator allows for ~infinite length without lossy precision and with minimal performance cost.
Example:
generate(2)
"03"
generate(2)
"72"
generate(2)
"20"
generate(3)
"301"
generate(3)
"436"
generate(3)
"015"
As you can see, even the zero are included initially which is an additional 10% loss just that, besides the fact that numbers prior to 10^n are not possible.
That is now a total of 20%.
Also, the other options have an upper limit on how many characters you can actually generate.
Example with cost:
var start = new Date(); var num = generate(1000); console.log('Time: ', new Date() - start, 'ms for', num)
Logs:
Time: 0 ms for 7884381040581542028523049580942716270617684062141718855897876833390671831652069714762698108211737288889182869856548142946579393971303478191296939612816492205372814129483213770914444439430297923875275475120712223308258993696422444618241506074080831777597175223850085606310877065533844577763231043780302367695330451000357920496047212646138908106805663879875404784849990477942580056343258756712280958474020627842245866908290819748829427029211991533809630060693336825924167793796369987750553539230834216505824880709596544701685608502486365633618424746636614437646240783649056696052311741095247677377387232206206230001648953246132624571185908487227730250573902216708727944082363775298758556612347564746106354407311558683595834088577220946790036272364740219788470832285646664462382109714500242379237782088931632873392735450875490295512846026376692233811845787949465417190308589695423418373731970944293954443996348633968914665773009376928939207861596826457540403314327582156399232931348229798533882278769760
More hardcore:
generate(100000).length === 100000 -> true
I would go with this solution:
Math.floor(Math.random() * 899999 + 100000)
More generally, generating a random integer with fixed length can be done using Math.pow:
var randomFixedInteger = function (length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}
To answer the question: randomFixedInteger(6);
You can use the below code to generate a random number that will always be 6 digits:
Math.random().toString().substr(2, 6)
Hope this works for everyone :)
Briefly how this works is Math.random() generates a random number between 0 and 1 which we convert to a string and using .toString() and take a 6 digit sample from said string using .substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.
This can be used for any length number.
If you want to do more reading on this here are some links to the docs to save you some googling:
Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
.toString(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
.substr(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
short with arbitrary precision
below code ALWAYS generate string with n digits - solution in snippet use it
[...Array(n)].map(_=>Math.random()*10|0).join``
let gen = n=> [...Array(n)].map(_=>Math.random()*10|0).join``
// TEST: generate 6 digit number
// first number can't be zero - so we generate it separatley
let sixDigitStr = (1+Math.random()*9|0) + gen(5)
console.log( +(sixDigitStr) ) // + convert to num
100000 + Math.floor(Math.random() * 900000);
will give a number from 100000 to 999999 (inclusive).
Based on link you've provided, right answer should be
Math.floor(Math.random()*899999+100000);
Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)
Here is my function I use. n - string length you want to generate
function generateRandomNumber(n) {
return Math.floor(Math.random() * (9 * Math.pow(10, n - 1))) + Math.pow(10, n - 1);
}
This is another random number generator that i use often, it also prevent the first digit from been zero(0)
function randomNumber(length) {
var text = "";
var possible = "123456789";
for (var i = 0; i < length; i++) {
var sup = Math.floor(Math.random() * possible.length);
text += i > 0 && sup == i ? "0" : possible.charAt(sup);
}
return Number(text);
}
let length = 6;
("0".repeat(length) + Math.floor(Math.random() * 10 ** length)).slice(-length);
Math.random() - Returns floating point number between 0 - 1
10 ** length - Multiply it by the length so we can get 1 - 6 length numbers with decimals
Math.floor() - Returns above number to integer(Largest integer to the given number).
What if we get less than 6 digits number?
That's why you have to append 0s with it.
"0".repeat() repeats the given string which is 0
So we may get more than 6 digits right?
That's why we have to use "".slice() method. It returns the array within given indexes. By giving minus values, it counts from the last element.
I created the below function to generate random number of fix length:
function getRandomNum(length) {
var randomNum =
(Math.pow(10,length).toString().slice(length-1) +
Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
return randomNum;
}
This will basically add 0's at the beginning to make the length of the number as required.
npm install --save randomatic
var randomize = require('randomatic');
randomize(pattern, length, options);
Example:
To generate a 10-character randomized string using all available characters:
randomize('*', 10);
//=> 'x2_^-5_T[$'
randomize('Aa0!', 10);
//=> 'LV3u~BSGhw'
a: Lowercase alpha characters (abcdefghijklmnopqrstuvwxyz'
A: Uppercase alpha characters (ABCDEFGHIJKLMNOPQRSTUVWXYZ')
0: Numeric characters (0123456789')
!: Special characters (~!##$%^&()_+-={}[];\',.)
*: All characters (all of the above combined)
?: Custom characters (pass a string of custom characters to the options)
NPM repo
I use randojs to make the randomness simpler and more readable. you can pick a random int between 100000 and 999999 like this with randojs:
console.log(rando(100000, 999999));
<script src="https://randojs.com/1.0.0.js"></script>
const generate = n => String(Math.ceil(Math.random() * 10**n)).padStart(n, '0')
// n being the length of the random number.
Use a parseInt() or Number() on the result if you want an integer.
If you don't want the first integer to be a 0 then you could use padEnd() instead of padStart().
I was thinking about the same today and then go with the solution.
var generateOTP = function(otpLength=6) {
let baseNumber = Math.pow(10, otpLength -1 );
let number = Math.floor(Math.random()*baseNumber);
/*
Check if number have 0 as first digit
*/
if (number < baseNumber) {
number += baseNumber;
}
return number;
};
Let me know if it has any bug. Thanks.
"To Generate Random Number Using JS"
console.log(
Math.floor(Math.random() * 1000000)
);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p id="demo"></p>
</body>
</html>
You can use this module https://www.npmjs.com/package/uid, it generates variable length unique id
uid(10) => "hbswt489ts"
uid() => "rhvtfnt" Defaults to 7
Or you can have a look at this module https://www.npmjs.com/package/shortid
const shortid = require('shortid');
console.log(shortid.generate());
// PPBqWA9
Hope it works for you :)
var number = Math.floor(Math.random() * 9000000000) + 1000000000;
console.log(number);
This can be simplest way and reliable one.
For the length of 6, recursiveness doesn't matter a lot.
function random(len) {
let result = Math.floor(Math.random() * Math.pow(10, len));
return (result.toString().length < len) ? random(len) : result;
}
console.log(random(6));
In case you also want the first digit to be able to be 0 this is my solution:
const getRange = (size, start = 0) => Array(size).fill(0).map((_, i) => i + start);
const getRandomDigit = () => Math.floor(Math.random() * 10);
const generateVerificationCode = () => getRange(6).map(getRandomDigit).join('');
console.log(generateVerificationCode())
generate a random number that must have a fixed length of exactly 6 digits:
("000000"+Math.floor((Math.random()*1000000)+1)).slice(-6)
Generate a random number that will be 6 digits:
console.log(Math.floor(Math.random() * 900000));
Result = 500229
Generate a random number that will be 4 digits:
console.log(Math.floor(Math.random() * 9000));
Result = 8751
This code provides nearly full randomness:
function generator() {
const ran = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
return Array(6).fill(null).map(x => ran()[(Math.random() * 9).toFixed()]).join('')
}
console.log(generator())
This code provides complete randomness:
function generator() {
const ran1 = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
const ran2 = () => ran1().sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
return Array(6).fill(null).map(x => ran2()[(Math.random() * 9).toFixed()]).join('')
}
console.log(generator())
parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random
Update:
This method has few flaws:
- Sometimes the number of digits might be lesser if its left padded with zeroes.

Round number to nearest .5 decimal

I'm looking for an output of
4.658227848101266 = 4.5
4.052117263843648 = 4.0
the closest I've gotten is
rating = (Math.round(rating * 4) / 4).toFixed(1)
but with this the number 4.658227848101266 = 4.8???
(Math.round(rating * 2) / 2).toFixed(1)
It's rather simple, you should multiply that number by 2, then round it and then divide it by 2:
var roundHalf = function(n) {
return (Math.round(n*2)/2).toFixed(1);
};
This works for me! (Using the closest possible format to yours)
rating = (Math.round(rating * 2) / 2).toFixed(1)
So this answer helped me. Here is a little bit o magic added to it to handle rounding to .5 or integer. Notice that the *2 and /2 is switched to /.5 and *.5 compared to every other answer.
/*
* #param {Number} n - pass in any number
* #param {Number} scale - either pass in .5 or 1
*/
var superCoolRound = function(n,scale) {
return (Math.round(n / scale) * scale).toFixed(1);
};
This is kinda late. But for someone who wants to round down to whole number or 0.5, you can try this:
function roundDown(number) {
var decimalPart = number % 1;
if (decimalPart < 0.5)
return number - decimalPart;
else
return number - decimalPart + 0.5;}
Late to this party, but I thought I would throw in a nice answer using a syntax I saw elsewhere, just in case someone comes across this in the future.
const roundDown = decimalNumber => {
return decimalNumber % 1 >= 0.5 ? +`${~~decimalNumber}.5` : ~~decimalNumber;
}
Explanation:
decimalNumber % 1 leaves you with only the decimal places
The + converts the string representation of your constructed number into a float, for consistency
~~decimalNumber drops the decimal places, leaving you with an integer
I assume you want to format the number for output and not truncate the precision. In that case, use a DecimalFormat. For example:
DecimalFormat df = new DecimalFormat("#.#");
df.format(rating);

JQuery create a random 16 digit number possible?

As the title says ... is it possible to create a random 16 digit number with jquery?
Just use:
Math.floor(Math.random()*1E16)
EDIT :
Note that there is about a 1/10 chance of a lower number of digits. If Math.random() generates something like 0.0942104924071337 then 0.0942104924071337 * 1E16 is 0942104924071337 which evaluates to 942104924071337; a 15 digit number.
The only way to 100% guarantee that the number is 16 digits in length is to have it be formed as a string. Using this method I would recommend #rjmunro's answer:
number = (Math.random()+' ').substring(2,10)+(Math.random()+' ').substring(2,10);
Not with jQuery, no, but you can do it with plain javascript.
If you want exactly 16 digits (possibly including leading 0s), I would start with Math.random(), convert to a string, pick 8 digits, and concatenate 2 runs together.
number = (Math.random() + '').substring(2,10)
+ (Math.random() + '').substring(2,10);
No, use JAVASCRIPT!
jQuery is not some magic genie.
This is a task which is much better suited for raw javascript. For example
var str = '';
var i;
for (i = 0; i < 16; i++) {
var number = Math.floor(Math.random() * 10) % 10;
str += number;
}
I just tried with #rjmunro 's answer.
Unfortunately, it does generate string less than 16digits,
but very rare, approxly once in 10 million times.
Here is my testing code, runs in nodejs:
'use strict';
var fs = require('fs');
var totalTimes = 100000000;
var times = totalTimes;
var fileName;
var writeStream;
while (times > 0) {
var key = (Math.random() + ' ').substring(2,10) + (Math.random() + ' ').substring(2,10);
times --;
if (key.length !== 16) {
var msg = 'a flaw key gened: ' + key + '\n';
// create a log file at first time
if (!fileName) {
fileName = 'log/flaw_key_' + new Date() + '.txt';
}
writeStream = fs.createWriteStream(fileName);
writeStream.write(msg);
writeStream.end();
}
if (times === 0) {
console.log(totalTimes + ' times key gened');
}
}
Also #Dimitri Mikadze 's answer generate less length string as well, so I eventually adopt a way with some concept of his solution:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Gen random digits string in specific length
* #param {Int} length of string
*
* #return {String}
*
*/
function genString(length) {
var times = length;
var key = '';
while (times > 0) {
times --;
key += getRandomInt(0, 9);
}
return key;
}
genString(16); // a 16 digits string
u can use this function to generate random digits, just pass minimum and maximum parameters
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
random 16 digit, usage
randomInt(0, 9999999999999999);
I know this question is old but this simple function will guarantee a 16 (or however many you want) character string every time without the 10% failure rate of other solutions. Can change it to a number if you need to.
function generate() {
let string = ""
while (string.length < 16) {
let number = Math.floor(Math.random() * 10).toString()
string += number
}
return string
}
I think this way is more beautiful:
const generateFixedLengthNumberInString = length =>
[...Array(length).keys()].reduce(
previousValue =>
previousValue + String(Math.floor(Math.random() * 10) % 10),
);
console.log(generateFixedLengthNumberInString(16))
// prints "0587139224228340"

Categories

Resources