Thread: Rounding off a double

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    1

    Unhappy Rounding off a double

    Does anyone have any sample code on how to round off a double to a whole number (nearest one)? Say for example rounding 2.12 to 3 and 2.7 to 3?

    Any help would be appreciated. I am learning C and have not found
    this info on the net so far (though it might be out there).

    Thanks.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    ceil() from math.h will do exactly what you give as examples. However, I believe what you actually want is
    Code:
    double round(double x)
    {
       return floor(x + 0.5);
    }
    That will round any number UP that ends with .5 or higher, and down if it's ending with .4999999 or lower. So 2.12 turns into 2.0, 2.7 turns into 3.0

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Although, if you're including math.h, there's a perfectly good round() function already there.

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    I think round() is C99 only - and so may not be available.
    Which is a good reason to call it "my_round()", or something similar, to avoid potential name collisions.

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying 2-d arrays
    By Holtzy in forum C++ Programming
    Replies: 11
    Last Post: 03-14-2008, 03:44 PM
  2. C++ to C Conversion
    By dicon in forum C Programming
    Replies: 7
    Last Post: 06-11-2007, 08:38 PM
  3. need some help with last part of arrays
    By Lince in forum C Programming
    Replies: 3
    Last Post: 11-18-2006, 09:13 AM
  4. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  5. Unknown Math Issues.
    By Sir Andus in forum C++ Programming
    Replies: 1
    Last Post: 03-06-2006, 06:54 PM