Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring `random` 3 digit number in Javascript

Tags:

javascript

I am trying to create the 3 digit random number using the following function:

gridView.generateData = function( size ) {

        var newData = [];

        var size = size || 100;
        var baseSize = 0;

        while( baseSize < size ) {
            baseSize++;
            newData.push( {
                "mk" : Math.floor( Math.random()*999 ) + 100 //3 digit
            } );
        }       
        return $q.all( newData );
    }

But in the out put object i see there is number of instance having 4 digit numbers to. how to insure only 3 digit using the above function?

thanks in advance.

like image 253
user2024080 Avatar asked May 11 '17 10:05

user2024080


People also ask

How do you limit Math random in JavaScript?

Generate a random number with a Max limit To do this, we would multiply the random number by 100. Math. random() will not return 1, so the value will be below 100.

How do you generate a random 3 digit number in Java?

You should create a Random object instead. Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.


2 Answers

if you want to generate 3 digit random numbers between 100 - 999 then you can try the below solution

Math.floor(Math.random()*(999-100+1)+100);
like image 72
subbu Avatar answered Sep 22 '22 09:09

subbu


You could use a variable for the digits. Then build the 10 potency otu of the digits and use this number as factor and as value to add for getting the digits with slice from the right side.

Later, you could return an obejct with a numerical value or some other formatting of the result.

function generateData(size) {
    var digits = 3;
    return Array.apply(null, { length: size || 100 }).map(function () {
        return Math.floor(Math.random() * Math.pow(10, digits) + Math.pow(10, digits)).toString().slice(-digits);
    });
}

console.log(generateData());
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 32
Nina Scholz Avatar answered Sep 20 '22 09:09

Nina Scholz