admin管理员组

文章数量:1194547

I'm looking to create a random number between two ranges that is a multiple of 10.

For example, if I fed the function the parameters 0, 100 it would return one of these numbers:

0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100

but nothing like 63 or 55.

And yes I'm aware this defeats the point of true "randomness", but I just need a quick easy way to get a number that's a multiple of 10 between two ranges.

Thanks. :)

I'm looking to create a random number between two ranges that is a multiple of 10.

For example, if I fed the function the parameters 0, 100 it would return one of these numbers:

0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100

but nothing like 63 or 55.

And yes I'm aware this defeats the point of true "randomness", but I just need a quick easy way to get a number that's a multiple of 10 between two ranges.

Thanks. :)

Share Improve this question asked Mar 3, 2011 at 21:49 JoshJosh 1,4215 gold badges23 silver badges33 bronze badges 1
  • 10 What happens if you pick a random integer number and multiply that by 10? – 6502 Commented Mar 3, 2011 at 21:51
Add a comment  | 

7 Answers 7

Reset to default 12

I guess it can help:

var randomnumber=Math.floor(Math.random()*11)*10

it's just one line:

function rand_10(min, max){
    return Math.round((Math.random()*(max-min)+min)/10)*10;
}
var a = 67;
var b = 124;
var lo = a + 10 - (a % 10) 
var hi = b - (b % 10)
var r = lo + 10 * parseInt(Math.random() * ((hi - lo)/10 + 1));
function rand(maxNum, factorial) { 
    return Math.floor(Math.floor(Math.random() * (maxNum + factorial)) / factorial) * factorial; 
};

Takes two parameter

  • maxNum Maximum number to be generated in random
  • factorial The factorial/incremental number

    1. multiplies the random number generated to the maxNum.
    2. Rounds down the result.
    3. Divides by the factorial.
    4. Rounds down the result.
    5. then multiplies again by the factorial.

Use a normal random number function like this one:

function GetRandom( min, max ) {
    if( min > max ) {
        return( -1 );
    }
    if( min == max ) {
        return( min );
    }

    return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}

As this will only return integers ("multiples of 1"), you can multiply by 10 and get only multiples of 10.

randomNumberMultipleOfTen = GetRandom(0,10) * 10;

Of course you can merge both into one function if you want to, I'll leave this as an exercise to you.

This seems to do the work

Math.floor(Math.random() * 10) * 10

If you modify that a little you can easily make it between any two numbers.

  1. Take the difference of the two parameters.
  2. Divide the difference by 10.
  3. Generate a random number from 0 to the result of the division.
  4. Multiply that by 10.

本文标签: javascriptMaking a random number that39s a multiple of 10Stack Overflow