#1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2001
    Location
    UK
    Posts
    543
    Rep Power
    58

    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. #2
  3. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Oct 2001
    Location
    New Zealand
    Posts
    1,774
    Rep Power
    24
    Something like:

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

    </script>
    </head>
    <body onLoad="init()">
    </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.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Seattle WA
    Posts
    863
    Rep Power
    14
    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.
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2001
    Location
    UK
    Posts
    543
    Rep Power
    58
    that is a seriously elegant solution!
    Wish I'd thought of that, so simple and effective

    Thanks so much!

IMN logo majestic logo threadwatch logo seochat tools logo