'generate 4 digit random number using substring

I am trying to execute below code:

var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);

I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?



Solution 1:[1]

That's because a is a number, not a string. What you probably want to do is something like this:

var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
  • Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
  • Multiplying by 9000 results in a range of [0, 9000).
  • Adding 1000 results in a range of [1000, 10000).
  • Flooring chops off the decimal value to give you an integer. Note that it does not round.

General Case

If you want to generate an integer in the range [x, y), you can use the following code:

Math.floor(x + (y - x) * Math.random());

Solution 2:[2]

This will generate 4-digit random number (0000-9999) using substring:

var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);

Solution 3:[3]

I adapted Balajis to make it immutable and functional.

Because this doesn't use math you can use alphanumeric, emojis, very long pins etc

const getRandomPin = (chars, len)=>[...Array(len)].map(
   (i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');


//use it like this
getRandomPin('0123456789',4);

Solution 4:[4]

$( document ).ready(function() {
  
    var a = Math.floor(100000 + Math.random() * 900000);   
    a = String(a);
    a = a.substring(0,4);
    alert( "valor:" +a );
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Solution 5:[5]

Your a is a number. To be able to use the substring function, it has to be a string first, try

var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);

Solution 6:[6]

You can get 4-digit this way .substring(startIndex, length), which would be in your case .substring(0, 4). To be able to use .substring() you will need to convert a to string by using .toString(). At the end, you can convert the resulting output into integer by using parseInt :

 var a = Math.floor(100000 + Math.random() * 900000)
 a = a.toString().substring(0, 4);

 a =  parseInt(a);

 alert(a);

https://jsfiddle.net/v7dswkjf/

Solution 7:[7]

The problem is that a is a number. You cannot apply substring to a number so you have to convert the number to a string and then apply the function.

DEMO: https://jsfiddle.net/L0dba54m/

var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);

Solution 8:[8]

$(document).ready(function() {
  var a = Math.floor((Math.random() * 9999) + 999);
  a = String(a);
  a = a.substring(0, 4);
});

Solution 9:[9]

// It Will Generate Random 5 digit Number & Char 
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {

    const value = Math.floor(Math.random() * char.length);

    randomvalue += char.substring(value, value + 1).toUpperCase();

}

console.log(randomvalue);

Solution 10:[10]

    function getPin() {
    let pin = Math.round(Math.random() * 10000);
    let pinStr = pin + '';

    // make sure that number is 4 digit
    if (pinStr.length == 4) {
        return pinStr;
       } else {
        return getPin();
       }
    }

   let number = getPin();

Solution 11:[11]

Just pass Length of to number that need to be generated

  await this.randomInteger(4);
  async randomInteger(number) {

    let length = parseInt(number);
    let string:string = number.toString();
    let min = 1* parseInt( string.padEnd(length,"0") ) ;
    let max =   parseInt( string.padEnd(length,"9") );

    return Math.floor(
      Math.random() * (max - min + 1) + min
    )
  }

Solution 12:[12]

This is quite simple

const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];

Solution 13:[13]

export const createOtp = (): number => {
      Number(Math.floor(1000 + Math.random() * 9000).toString());
}