Generate 4 digit random number using substring

I am trying to execute the code below:

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

I get an error, as undefined is not a functionin line 2, but when I try to do alert(a)it has something. What is wrong here?

+20
source share
8 answers

This is because it ais 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);
Run codeHide result
  • Math.random() will generate a floating point number in the range [0, 1) (note that 1 is excluded from the range).
  • Multiplication by 9000 results in the range from [0, 9000].
  • Adding 1000 results to the range [1000, 10000].
  • , . , .

[x, y), :

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

4- (0000-9999) :

var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
+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>
Hide result
+1

a - . substring, string,

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

4- .substring(startIndex, length), .substring(0, 4). .substring(), a .toString(). parseInt:

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

 a =  parseInt(a);

 alert(a);

https://jsfiddle.net/v7dswkjf/

0

, a . substring , , .

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

var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
0
$(document).ready(function() {
  var a = Math.floor((Math.random() * 9999) + 999);
  a = String(a);
  a = a.substring(0, 4);
});
0
// 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);
0

All Articles