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

拟墨画扇 提交于 2019-11-27 20:26:47

问题


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


回答1:


What about:

Math.floor(Math.random()*90000) + 10000;



回答2:


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;



回答3:


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)



回答4:


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.



来源:https://stackoverflow.com/questions/2175512/javascript-expression-to-generate-a-5-digit-number-in-every-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!