Thread: Rounding up float numbers

  1. #1
    Registered User godly 20's Avatar
    Join Date
    Jan 2011
    Location
    Italy
    Posts
    29

    Rounding up float numbers

    Is there a function or an algorithm to round up float numbers to 2 digits after the radix point (comma).
    Example: 3.1457 ->Rounds up to-> 3.14
    "A Computer in every desk and in every home, running Microsoft software."

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    If it's for display purposes, look up std::setprecision. Otherwise, add .005 or however it would work mathematically.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    If you need the mathematical result (rather than display purposes) use std::ceil(value*100.0)/100.0

    There are some limits on the range of values this works for (and this assumes a positive value) but, if you are asking the question, you are unlikely to be working outside the relevant range.
    Last edited by grumpy; 06-12-2011 at 06:25 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Code:
    double round_floating_2(double x)
    {
        return x - std::fmod(x, 0.01);
    }
    Works without these limits.

  5. #5
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Quote Originally Posted by godly 20 View Post
    Is there a function or an algorithm to round up float numbers to 2 digits after the radix point (comma).
    Example: 3.1457 ->Rounds up to-> 3.14
    Btw, it is rounding down, isn't it? My code was provided to work with the example.

  6. #6
    Registered User godly 20's Avatar
    Join Date
    Jan 2011
    Location
    Italy
    Posts
    29
    Yes, it's rounding down.
    "A Computer in every desk and in every home, running Microsoft software."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-24-2011, 02:28 PM
  2. Rounding a float and casting to an int
    By pollypocket4eva in forum C Programming
    Replies: 4
    Last Post: 01-09-2009, 09:42 AM
  3. Rounding/truncating float to int
    By Zzaacchh in forum C++ Programming
    Replies: 4
    Last Post: 07-02-2008, 11:21 PM
  4. Rounding float problem.....
    By manny in forum C Programming
    Replies: 6
    Last Post: 03-26-2007, 09:23 PM
  5. Rounding Float- Return not happening ?
    By pprabhakar in forum C Programming
    Replies: 5
    Last Post: 05-14-2006, 09:44 AM

Tags for this Thread