Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
May 1st, 2002, 07:45 AM
 rolty
Contributing User

Join Date: Jun 2001
Location: UK
Posts: 543
Time spent in forums: 4 Days 1 h 36 m 49 sec
Reputation Power: 57
random number in javascript

I know how to generate a random number, also how to round it, I can multiply it too, but how on earth do I generate a round number between 100 and 999? I can get a random number from 0 to 999, but need to lose everything less than 3 digits???

#2
May 1st, 2002, 08:32 AM
 binky
Contributing User

Join Date: Oct 2001
Location: New Zealand
Posts: 1,774
Time spent in forums: 1 Day 58 m 15 sec
Reputation Power: 24
Something like:

<html>
<script type="text/javascript">
function getRandom() {
thisNumber = Math.floor(Math.random() * 1000)
if (thisNumber < 100) {
getRandom()
} else {
return thisNumber
}
}
function init() {
}

</script>
</body>
</html>

would work. In this case, what should happen is that a random number is generated between 0 and 999. The number is tested, if it's less than 100 the function is called again until it is above 100. If it is above 100 then it is returned to the calling command.
It has to be done as a recursive function.
__________________
Smartfone Warehouse

#3
May 1st, 2002, 02:02 PM
 MJEggertson
Contributing User

Join Date: Jan 2002
Location: Seattle WA
Posts: 863
Time spent in forums: 22 sec
Reputation Power: 13
Somewhat more efficient would be

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

Generates a random number between 100 and 999 directly, avoiding issues with successive calls to Math.random() generating consecutive numbers less than 100. Not really an issue on today's fast computers, but good coding practice is always worth it.

#4
May 1st, 2002, 02:22 PM
 rolty
Contributing User

Join Date: Jun 2001
Location: UK
Posts: 543
Time spent in forums: 4 Days 1 h 36 m 49 sec
Reputation Power: 57
that is a seriously elegant solution!
Wish I'd thought of that, so simple and effective

Thanks so much!

 Viewing: Dev Shed Forums > Web Design > JavaScript Development > random number in javascript