5

How can I implement a simple function in JavaScript that generates a random positive number that consists of only two digits?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yasmine Ra'fat
  • 97
  • 1
  • 1
  • 5
  • You mean, 0..99? 10..99? – John Dvorak Mar 31 '13 at 22:12
  • What do you mean by "negative"? To get a specific range, just scale the uniform distribution, and then round to integers. I'm surprised you haven't found an example doing that. – John Dvorak Mar 31 '13 at 22:17
  • 1
    This can't be the first question to scale and round random numbers. Candidate: *[Generating random whole numbers in JavaScript in a specific range](https://stackoverflow.com/questions/1527803/)* – Peter Mortensen Apr 18 '22 at 13:47

2 Answers2

24

For a random number between 10 and 99, use:

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

jsFiddle demo: http://jsfiddle.net/zjLY6/

metadept
  • 7,831
  • 2
  • 18
  • 25
  • Isn't this subject to floating point rounding errors? What if 10, when converted to floating point just before the addition, is actually represented as 9.9999987183884837499393? Even if it happens to work for 10, it may not be generally applicable. – Peter Mortensen Apr 18 '22 at 13:18
  • Shouldn't the 10 be outside the parentheses? – Peter Mortensen Apr 18 '22 at 14:15
7

Try

Math.random().toFixed(2)*100
ama2
  • 2,611
  • 3
  • 20
  • 28