How to generate a Random Number of required length

My question: I would like to generate a random number in the given range.
For eg: I would like to generate a value between 234545 and 5565756

Iā€™ve already tried: YES

Hello there,

to generate a random number between 234545 and 5565756, you can do like this.

function randInt(min, max) {
   return Math.round((Math.random() * Math.abs(max - min)) + min);
}

console.log("Random integer: " + randInt(234545, 5565756));

I hope itā€™ll help you.
Best Regards,
Rishi Purwar

2 Likes

Thank you for your quick reply

2 Likes

@tulasi Welcome to the Community :partying_face:

You can create function like below,

let min = 234545;
let max = 5565756;
// for generating random number 
function randomNumber(min, max) { 
    return Math.random() * (max - min) + min;
} 
console.log(Math.round(randomNumber(min, max)));

to reuse it

Else you can directly use

console.log(Math.round(Math.random() * (5565756 - 234545) + 234545));

And assign this to another variable as per your needs :blush:

1 Like

Thank you very much for your quick support. I am new to PostMan

1 Like

I saw @thefierycoderā€™s reply after posting :raised_hands: Both are same :blush:

1 Like

@bpricilla Can you please help me with this?

1 Like

@tulasi No worries at all!! We too started in your place once :blush:

All the best for your learning :partying_face:

1 Like

Hi people, im new too in postmanā€¦ i have the same doubt as this user has.

But i cant do the things work ^^U

The thing is i want to create a global variable to random age (from 00 to 100 years old) and i use to do this in the pre request script as
pm.globals.set(ā€œedadglobalā€, pm.variables.replaceIn(ā€˜{{$randomInt}}ā€™));
But i dont know how to do the things work to have the numbers in the range i wantā€¦ i tried doing the ways u said before but maybe those are for the body? i dunno ^^U thanks for reading :slight_smile:

EDIT
Its correct to do it in this way?

const edad = Math.floor((Math.random()*100)+1);

console.log (edad)

pm.globals.set(ā€œedadaleatoriaā€, edad)

Thanks a ton :smiley:

@jmcgv

let x = Math.floor(Math.random() * 100; // between 0 and 100
let y = Math.floor((Math.random() * 100) + 1); // between 1 and 100

for (let i = 0; i < 50; i++) {
    console.log(Math.floor(Math.random() * 100));
}

JavaScript Math random() Method (w3schools.com)

You can also use the Lodash library that is built into Postman.

Lodash JS Tutorial with Examples (javaguides.net)

for (let i = 0; i < 40; i++) {
    console.log(r = _.random(0, 100));
}

Thanks for ur answer, i will study it and try it!! Thanks a ton :slight_smile: