12

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.

user2024080
  • 1
  • 14
  • 56
  • 96

9 Answers9

24

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);
subramanian
  • 1,125
  • 1
  • 12
  • 12
  • 3
    would be nice to mention that `~~` does the same as `Math.floor` ;) +1 – King Reload May 11 '17 at 12:48
  • Why have you kept `999-100+1` as an equation, why not just change it to `900`? – Olian04 Jan 08 '18 at 22:27
  • 1
    Math.floor(Math.random()*(end Number - start Number +1) + start Number) - generic formula to generate a random number with in range. (end Number - start Number + 1 ) = the number of possible results Math.random() = 0 to 1 . since we need numbers between 100 and 999 in this case we want to add the start number – subramanian Jan 09 '18 at 10:32
3

The problem in your code is that you are using +100 in your number, it will give 4-digits numbers for all generated numbers that are greater than 900: 900+100=1000.

Solution:

If you want to ensure that your number is always a 3-digits number(>=100), you can do it like this:

var number;
do {
  number = Math.floor(Math.random() * 999);
} while (number < 100);

You should just test upon this number until it's >=100, instead of adding 100 to it because it can give you numbers with 4 digits.

Demo:

Here's a live Demo which allows only numbers between 100 and 999:

var number;
do {
  number = Math.floor(Math.random() * 999);
} while (number < 100);
console.log(number);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This is the only one that HASNT generated 4 and 2 digit numbers so far. This should be the accepted answer :P. Have an upvote miss. – Mister SirCode Sep 23 '19 at 14:23
1

I had to face myself almost the same problem (generating "something" in the range from "000" to "999") and decided to use:

var round = 10;
while( round > 0 ) {
    round--;
    console.log( Math.random().toString().concat("0".repeat(3)).substr(2,3) );
}                

Should remember that Math.random() returns a random number between 0 (inclusive), and 1 (exclusive). You may get "0.001" or even "0.0001" (that is lot of leading zeros on the decimal part), so multiply by 1000 or 999 would not lead to the result I desired.

daghemo
  • 156
  • 6
0

Don't add 100. Otherwise you will overflow.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/16093885) – Shakti Phartiyal May 11 '17 at 20:05
  • 1
    @DanielA.White Firstly this does not work for the OP and secondly, its too short for an answer, no explanation therefore marked as low quality post. You with 128K+ reputation should know that. :) – Shakti Phartiyal May 11 '17 at 20:08
  • @ShaktiPhartiyal theres nothing as too short of an answer. – Daniel A. White May 11 '17 at 20:10
  • @DanielA.White I do not wish to disagree with you. but then why was your answer marked as a low quality post and what does **length** stand for in _This answer was flagged as low-quality because of its length and content._ – Shakti Phartiyal May 11 '17 at 20:15
0

You were on the right path, but that +100 was not necessary, as shown below:

gridView.generateData = function( size ) {
    var newData = [];

    var size = size || 100;
    var baseSize = 0;
    var digit = ~~( Math.random()*999 );

    while(digit < 100) {
        digit = ~~( Math.random()*999 );
    }

    if(digit >= 100) {
        while( baseSize < size ) {
            baseSize++;
            newData.push( {
                "mk" : digit //3 digits
            });
        }

        return $q.all( newData );
    }
}

As Math.random() returns a float between 0 and 1, so just multiply it by 999 without the +100.

King Reload
  • 2,780
  • 1
  • 17
  • 42
  • Your suggestion give even single and double digits too.. https://jsfiddle.net/3gwebtrain/mvuLvbn2/ – user2024080 May 11 '17 at 10:31
  • @user2024080 that's a separate issue theres patterns on how to pad leading 0's if thats waht you want. – Daniel A. White May 11 '17 at 10:33
  • @user2024080 so you only want it to be above the 100? then you need to put the variable outside of the send and just put in an `if` statement to check if its above the 100 – King Reload May 11 '17 at 10:34
  • Why "multiply it by 999"? Math.random() returns a random number between 0 (inclusive), and 1 (exclusive). – daghemo May 03 '20 at 08:47
0

Your code problem

if you add +100.its append 4 digit number .If you remove the 100. its append below 3 digit number

So better use like this, parseInt(Math.floor(math.random()*100000).toString().substring(0,3)) .Generate random num with above 4 digit, then cut the string with 3digit. And finally convert into integer .In this method they prevent the below and above3 digit value.

var newData = [];

        var size =100;
        var baseSize = 0;

        while( baseSize < size ) {
            baseSize++;
            newData.push( {
                "mk" : parseInt(Math.floor( Math.random()*100000).toString().substring(0,3))
            } );
        }       
      console.log( newData );
Community
  • 1
  • 1
prasanth
  • 22,145
  • 4
  • 29
  • 53
0
var number = 0;
var digits = '';

for (i = 0; i < 3; i++) {
    number = Math.floor(Math.random() * 10);
    digits = digits + number.toString();
}
user12700
  • 63
  • 4
0

The accepted answer doesn't allow for a three digit number below 100 (ie. 001).

This oneliner will return from 000 to 999.

var rand='',d=0; while(d<3){rand+=Math.floor(Math.random()*10);d++}
PromInc
  • 1,174
  • 7
  • 12