Thread: Newbie question: rounding numbers

  1. #1
    Registered User cantore's Avatar
    Join Date
    Feb 2006
    Posts
    8

    Post Newbie question: rounding numbers

    Hi all, I'm fairly new to the C language and I'm having issues with rounding numbers.
    I'm writing a program that asks the user to input a number (this number is a variable of type double).
    The user can obviously enter any number, for example, 14.45675. What I'm trying to do is to get that number and round it off to two decimals (so it will be 14.46) to proceed with further calculations that are related with dollars/cents (hence the reason why I only want two decimal places).
    In other words, I'm trying to round the number to two decimals and 'chop off' the rest of the decimals so they don't interfere later on with my calculations.
    I hope this is clear enough.

    Thanks in advance.

  2. #2
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    Are you trying to truncate (that is, chop off) or round to the nearest .01? Rounding of 0.999 gives 1.00, truncation gives 0.99.

    Note that not all decimal fractions can be represented exactly by floating point values, and even after rounding and/or truncation, you might find some stray non-zero digits beyond your desired significant digits.
    Last edited by filker0; 02-03-2006 at 10:04 PM.
    Insert obnoxious but pithy remark here

  3. #3
    Registered User cantore's Avatar
    Join Date
    Feb 2006
    Posts
    8
    Thanks for your quick reply filker. I'm trying to round to the nearest .01.
    Any ideas?

  4. #4
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    A few.

    I have used a C compiler with a math package that included a set of "round()" functions that did precision rounding, but they were non-standard.

    If you include <math.h>, you can use (when dealing with doubles) the expression
    Code:
    double roundedval = round(oldval * 100.0) / 100.0;
    This will result in a rounding, as desired, within the limitations of the internal floating point representation.
    Insert obnoxious but pithy remark here

  5. #5
    Registered User cantore's Avatar
    Join Date
    Feb 2006
    Posts
    8
    My book mentions the round() function too, and it gives an example, but they use the "tools.h" library which I don't seem to have ( I get a 'no such file or directory...' error message). I did try your suggestion, including the <math.h> but it tells me that round is an undeclared identifier.

  6. #6
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    math.h is a standard C header.

    When you use it, on Linux (and other Unix varients) you must also use the "-lm" switch when linking, as in
    Code:
    gcc -o example example.c -lm
    This makes it include referenced functions from libm.a (or the equivilent).

    If your compiler package does not supply math.h and the math library, I'm surprised.

    However, you can write your own round() function:
    Code:
    double myround(double value, int places)
    {
        double  adjust = 1.0;
        long temp;
    
        for (;places > 0; places--)
        {
            adjust *= 10;
        }
        temp = (long)((value * adjust) + 0.5);
        return (double)temp / adjust;
    }
    Note that this function may not have exactly the same results as using round(), but it should give you good values. I've not tested this code -- I just typed it in here -- but I think that it's correct. I've not commented it, so see if you can figure out what it does and how it does it.
    Last edited by filker0; 02-03-2006 at 11:16 PM. Reason: Fix typo
    Insert obnoxious but pithy remark here

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Don't use floats for money amounts, use an integer to count the number of cents.
    When you want to display an amount, use %100 to extract cents and /100 to extract dollars.

    http://en.wikipedia.org/wiki/Floating_point

  8. #8
    Registered User cantore's Avatar
    Join Date
    Feb 2006
    Posts
    8
    Thanks everybody for the help, after a few headaches I think I got it. Thanks again

  9. #9
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    round was added in C99, so I wouldn't be surprised if some compilers didn't support it.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I think printf() automatically rounds floating point numbers:
    Code:
    printf("%.2f\n", 1.249);
    Suspected output:
    Code:
    1.25
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Here's an implemetation of round:
    Code:
    double newround(double x) {
        return (int)(x + .5);
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie Question - fflush(stdin) & fpurge(stdin) on Mac and PC
    By tvsinesperanto in forum C Programming
    Replies: 34
    Last Post: 03-11-2006, 12:13 PM
  2. Creating a file with random numbers question??
    By Hoser83 in forum C Programming
    Replies: 28
    Last Post: 02-16-2006, 02:11 PM
  3. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM
  4. Newbie question on numbers.
    By thes in forum C++ Programming
    Replies: 14
    Last Post: 06-17-2002, 07:18 AM
  5. A (complex) question on numbers
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 02-03-2002, 06:38 PM