Thread: Rounding

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    41

    Rounding

    How do I do if I want to round numbers to the closest number with X digits to the left and thwen just zeroes. I give an example to give a better idea:

    69486 rounded with 2 digits is 69000
    2623 is 2600
    93 is 93
    2000 is 2000

    What´s the easist way to do this? Is there any special API for it?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Are we talking about integers or floating point?

    As far as I'm aware, there is no library or API function to do this, so you'll have to do it "by hand", and it's relatively easy to do for integers, a bit more comlicated for floating point.

    For integer, you essentially need to find out the number of digits in the number, and then divide and multiply the number so that you end up with the number you want. You should also consider that 69586 is 70000 when you round it, so you need to add a bit before you chop off the number.

    In this case, the code would look like this:
    Code:
    int x = 69586;
    x += 500;
    x /= 1000;
    x *= 1000;
    This is of course not generic, but it's not terribly hard to write a function that does it for "any number with any number of digits".

    --
    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
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    Ok, thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rounding off a double
    By C-Dummy in forum C Programming
    Replies: 3
    Last Post: 06-23-2008, 11:45 AM
  2. setprecision() - can I count on it rounding or not?
    By major_small in forum C++ Programming
    Replies: 2
    Last Post: 11-23-2005, 02:26 PM
  3. Rounding errors
    By Buckshot in forum C++ Programming
    Replies: 15
    Last Post: 08-16-2005, 09:11 PM
  4. preventing rounding problems with doubles
    By mccoz in forum C++ Programming
    Replies: 9
    Last Post: 11-05-2004, 09:23 AM
  5. Help with rounding a number
    By nickk in forum C Programming
    Replies: 3
    Last Post: 06-02-2004, 11:44 AM