Thread: Round off float to integer

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    106

    Round off float to integer

    Hi Guys,
    This isn't homework, it's for a personal project

    I have a float values I'd like to round off to the nearest integer value.
    That is to say, if the float value is 44.234533, the integer value should
    be 44. If the float value is 44.682101, the integer value should be 45.

    How do I do this?
    Thanks, Art.

  2. #2
    Registered User
    Join Date
    Mar 2013
    Posts
    10
    maybe it helps..

    ceil(x) <math.h> Returns the smallest integral
    value that is not less than x :
    if x is 45.23 , ceil(x) is 46.0

    floor(x) <math.h> Returns the largest integral value
    that is not greater than x :
    if x is 45.23 , floor(x) is 45.0

  3. #3
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Here's a neat little trick:

    Code:
    round_to_nearest_int( double x ) {
       return floor( x + 0.5 );
    }
    Can you figure out for yourself why this works?
    Code:
    while(!asleep) {
       sheep++;
    }

  4. #4
    Registered User
    Join Date
    Jan 2013
    Posts
    106
    No, I can't see it, but I did figure out this much:

    Code:
    float x = 44.56;
    float w;
    
    w = x - floor(x);
    if (w < 0.5) {// round down} else {// round up};

  5. #5
    Registered User
    Join Date
    Jan 2013
    Posts
    106
    Yes I can see why now, it's the same thing

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Round float to 2 decimal places
    By tesla in forum C Programming
    Replies: 8
    Last Post: 09-15-2009, 12:51 AM
  2. round a number to superior integer
    By nevrax in forum C Programming
    Replies: 5
    Last Post: 03-30-2007, 02:57 AM
  3. why does float round up
    By Unregistered in forum C Programming
    Replies: 8
    Last Post: 02-21-2002, 04:26 PM
  4. How To Round A Float To Two Decimal Points?
    By shahid in forum C++ Programming
    Replies: 2
    Last Post: 11-09-2001, 11:24 AM
  5. Is this the best way to round up a float ?
    By The Gweech in forum C++ Programming
    Replies: 3
    Last Post: 09-12-2001, 07:39 AM