How can I implement a simple function in JavaScript that generates a random positive number that consists of only two digits?
-
You mean, 0..99? 10..99?– John DvorakMar 31, 2013 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 DvorakMar 31, 2013 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– Peter MortensenApr 18, 2022 at 13:47
Add a comment
|
2 Answers
For a random number between 10 and 99, use:
Math.floor(Math.random() * 90 + 10)
jsFiddle demo: http://jsfiddle.net/zjLY6/
-
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
-
Try
Math.random().toFixed(2)*100
-
1This can give results like:
56.99999999999999
. It would be better to applyMath.floor
to the result Oct 26, 2021 at 21:34