SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    John 8:24 JREAM's Avatar
    Join Date
    Sep 2007
    Location
    Florida
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Math.floor vs Math.ceil

    Hey guys I was trying to generate a random number and looked at methods other people use and I always see Math.floor being used and wonder if their is any specific reason.

    A technique multiplying by 10 and adding 1 to makeup for the rounded down:
    document.write(Math.floor(Math.random()*10+1));

    This seems more practical:
    document.write(Math.ceil(Math.random()*10));

    ceil: Returns the value of a number rounded upwards to the nearest integer
    floor: Returns the value of a number rounded downwards to the nearest integer

    Does this matter a whole lot? Im wondering if there is a disadvantage to ceil, as I haven't found a bad roundup yet.. Sorry Im not that great with math

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Random integers are often used to assign array items as values.

    Math.floor(Math.random()*array.length) will return an index between 0 and the largest array index.

    Math.ceil in the same expression will never return array[0] and will occasionally return array[array.length], which is one more than the largest array item, and an error if you don't catch it.

    Suit yourself, but often there is a reason one method is used instead of another.

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,868
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The difference between the two versions is when the number doesn't have any decimal places in which case floor+1 will return a number 1 greater than ceil since when there are no decimals floor and ceil both round the number to itself.
    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="^$">

  4. #4
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You would have to multiply a javascript random number by at least 10e15 to force an integer- too large for a javascript array, by about 6 orders of magnitude.


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
  •