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.
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.
You should create a Random object instead. Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.
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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With