1

I wan't to generate a random number and use it as a class name for an element.

Math.random();

This will generate a random number '0.7220265011042561' Since this will be used as a class within the class attribute of an element, the decimal will surely cause problems and most likely isn't valid.

How can I generate a random whole number?

  • If @Shabbb only wants a random whole number of unfixed, arbitrary length, then yes it's a duplicate. If he wants one with a set length, it's arguable that the aforementioned duplicate question is only part of his question and therefore not a duplicate. – timolawl Apr 16 '16 at 04:31

3 Answers3

3
Math.round( Math.random()*10000000 )
Phrogz
  • 296,393
  • 112
  • 651
  • 745
3

This will generate a random whole number between 1 and 100.

Math.floor((Math.random() * 100) + 1);

Change the 100 part to redefine your range.

1

Add however many significant digits you want with the 100000 part:

Math.floor(Math.random() * 100000);

If you want them the same length, for smaller numbers (e.g., 5), here's a left-padded version:

var sigFig = // (put the number of significant digits you want here)
var number = Math.floor(Math.random() * Math.pow(10, sigFig));
var numStr = String(number);
while (numStr.length < sigFig) {
    numStr = '0' + numStr;
}

// do stuff with numStr

Edit: Moved the significant figure to a variable.

timolawl
  • 5,434
  • 13
  • 29