SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2009
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Making Random Number

    I am trying to make a random number between 1 and 1,000. I have a code that seems to work correctly, but I don't completely understand it and after looking online I think it might be wrong.

    Code:
    var rnd = Math.floor(Math.random()*999)
    Thanks.

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,788
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    That is giving random numbers between 0 and 998 not between 1 and 1000.

    Math.random() returns a random number that is greater than or equal to zero and less than one.

    If you multiply that by 1000 you get a random number greater than or equal to zero and less than 1000.

    Math.floor will remove the decimal portion leaving you with an integer between zero and 999.

    Add one to it to get a number between 1 and 1000.

    Code:
    var rnd = Math.floor(Math.random()*1000)+1;
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Zealot
    Join Date
    Dec 2009
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, I really don't like Javascript too much. Its so much different then other languages.

    Thanks for the reply.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •