How can I implement a simple function in JavaScript that generates a random positive number that consists of only two digits?
Asked
Active
Viewed 2.2k times
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
-
1This 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 Answers
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
-
7
Try
Math.random().toFixed(2)*100

ama2
- 2,611
- 3
- 20
- 28
-
1This can give results like: `56.99999999999999`. It would be better to apply `Math.floor` to the result – Lucas Colombo Oct 26 '21 at 21:34