Skip to content

Instantly share code, notes, and snippets.

@brunomonteiro3
Created May 10, 2017 01:34
Show Gist options
  • Save brunomonteiro3/27af6d18c2b0926cdd124220f83c474d to your computer and use it in GitHub Desktop.
Save brunomonteiro3/27af6d18c2b0926cdd124220f83c474d to your computer and use it in GitHub Desktop.
Generate random number between two numbers in JavaScript
function randomIntFromInterval(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
@lourdrivera123
Copy link

lourdrivera123 commented Jun 18, 2018

Is it possible to have like a test case for this one to ensure that it doesn't return a number below min and over max?

@Pharaoh00
Copy link

@lourdrivera123 you do not need a "test case" for this situation because the "algorithm" does not return values greater than minimum and maximum. For more explanation about it you can read the mozilla guide.

But if you really want to, you can do something like that:

    function randomIntFromInterval(min,max){
        let result =  Math.floor(Math.random()*(max-min+1)+min);
        if(result < min){
            result = min;
        }
        else if(result > max){
            result = max;
        }
        console.log(result);
    }

Again, you don't need to check this function, because you pass the min/max. On the mozilla guide, for the Math.random, you can find other random generator's.

@Gropitel
Copy link

function Numbers(min,max){
console.log(Math.floor(Math.random()*(max-min+1)+min));
}
Numbers(15, 20)

@islam-fawzy25
Copy link

Thanks it´s working good 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment