JavaScript expression to generate a 5-digit number in every case
Asked Answered
E

5

84

for my selenium tests I need an value provider to get a 5-digit number in every case. The problem with javascript is that the api of Math.random only supports the generation of an 0. starting float. So it has to be between 10000 and 99999.

So it would be easy if it would only generates 0.10000 and higher, but it also generates 0.01000. So this approach doesn't succeed:

Math.floor(Math.random()*100000+1)

Is it possible to generate a 5-digit number in every case (in an expression!) ?

Endothelium answered 1/2, 2010 at 8:46 Comment(0)
Q
205

What about:

Math.floor(Math.random()*90000) + 10000;
Qualifier answered 1/2, 2010 at 8:51 Comment(2)
Adding the 10000 at the end does nothing.Counterforce
Check it again, @BenBrown. Without the 10000 you can have numbers with less than 5 digits.Qualifier
V
62

Yes, you can create random numbers in any given range:

var min = 10000;
var max = 99999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;

Or simplified:

var num = Math.floor(Math.random() * 90000) + 10000;
Venettavenezia answered 1/2, 2010 at 8:49 Comment(0)
H
25

if you want to generate say a zipcode, and don't mind leading zeros as long as it's 5 digits you can use:

(""+Math.random()).substring(2,7)
Homologous answered 1/2, 2010 at 11:58 Comment(3)
I'm curious how the performance of this would compare to the other methods. This one appeals to me, but it seems like the string conversion and then substring could be expensive.Cnidus
Mmm, Math.random() is not guaranteed to return at least N digits. I just tried it with firefox, (""+Math.random()).substring(2,7) can return XYZ or XYWZ which is 3/4 digits.Stagey
I'm using it and cryingSynovia
W
6

What about this?

var generateRandomNDigits = (n) => {
  return Math.floor(Math.random() * (9 * (Math.pow(10, n)))) + (Math.pow(10, n));
}

generateRandomNDigits(5)
Whitelaw answered 16/7, 2020 at 20:36 Comment(0)
V
1

You can get a random integer inclusive of any given min and max numbers using the following function:

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

For more examples and other use cases, checkout the Math.random MDN documentation.

Voccola answered 4/8, 2016 at 23:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.