Thread: Rounding float to nearest integer

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

    Rounding float to nearest integer

    Hi Guys,
    I have a situation where a float calculation is made,
    and the result is converted back to an integer.


    Is there a neat solution to convert to the nearest integer,
    rather than just copying the float to the integer to always round down?


    So instead of this:
    Code:
    float afloat = 5.9;
    int aninteger = 0;
    
    
    aninteger = afloat; // aninteger = 5

    Something neater, and hopefully faster than this:


    Code:
    float afloat = 5.9;
    int aninteger = 0;
    
    
    aninteger = afloat; // aninteger = 5
    afloat = afloat - aninteger; // afloat = 0.9
    if (afloat > 0.5) {aninteger++;} // aninteger = 6

    Or is this the best I can hope for?
    Cheers, Brek.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well it depends on what exactly you want from your rounding.

    value = floor(value+0.5); would round 5.9 to 6 like your example.

    You can trick floor into working for other decimal places by sliding the point.

    value = floor(value * 100 + 0.5) / 100; would round something like 4.668 to 4.67 or 1.234 down to 1.23.

  3. #3
    Registered User
    Join Date
    Jan 2013
    Posts
    106
    Yes ok thanks Really just anything above 0.5 to the next integer will do for now.
    I’m using an old C30 compiler that doesn’t have round() functions in math library.

    You didn’t catch that I forgot negative numbers exist though!

    I just did a check if the number is below 0.0, and used a slightly different
    version of the above in that case.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rounding to the nearest cent problem
    By Ram999 in forum C Programming
    Replies: 6
    Last Post: 02-05-2014, 03:07 PM
  2. Rounding to the nearest dollar
    By alkamenes in forum C++ Programming
    Replies: 2
    Last Post: 11-19-2009, 07:44 AM
  3. Converting float to integer... without rounding!
    By hebali in forum C Programming
    Replies: 6
    Last Post: 10-05-2008, 06:58 PM
  4. Rounding a float to the nearest half
    By kzar in forum C Programming
    Replies: 4
    Last Post: 04-01-2005, 10:07 PM
  5. rounding to nearest penny
    By sizzle_chest in forum C++ Programming
    Replies: 6
    Last Post: 09-06-2001, 03:57 PM

Tags for this Thread