5

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

3

2 Answers 2

24

For a random number between 10 and 99, use:

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

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

2
  • 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. Apr 18, 2022 at 13:18
  • Shouldn't the 10 be outside the parentheses? Apr 18, 2022 at 14:15
7

Try

Math.random().toFixed(2)*100
1
  • 1
    This can give results like: 56.99999999999999. It would be better to apply Math.floor to the result Oct 26, 2021 at 21:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.