Thread: rounder routine

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    16

    rounder routine

    Do people have a usual function they use when rounding
    floats off to two decimal places (in order to represent
    monetary amounts)?

    I am asking because my program takes a percentage of a
    dollar and cents amount, which can give a result of more
    than two decimal places.

    A friend suggested that I preserve the amount and just
    print a rounded-off amount to screen. Good idea?

    Miki
    [email protected]

  2. #2
    Registered User C_Coder's Avatar
    Join Date
    Oct 2001
    Posts
    522
    A friend suggested that I preserve the amount and just
    print a rounded-off amount to screen.
    Sounds like a good idea
    Code:
    #include <stdio.h>
    
    int main(void)
    {
       float num = 10.53456;
    
       printf("%.2f", num);   // The .2 specifies the number of decimal places
    
       return 0;
    }
    All spelling mistakes, syntatical errors and stupid comments are intentional.

  3. #3
    Registered User
    Join Date
    Feb 2002
    Posts
    16
    Thanks. I have two more questions.

    First, does that code round up in case of a third decimal
    place that is 5 or more?

    Second, can you use <cstdio> instead of <stdio.h> in C++
    programs, as I prefer the newer header files?

    Miki
    [email protected]

  4. #4
    Registered User C_Coder's Avatar
    Join Date
    Oct 2001
    Posts
    522
    First, does that code round up in case of a third decimal
    place that is 5 or more?
    Yup, change the value to 10.53656 and try it.
    Second, can you use <cstdio> instead of <stdio.h> in C++
    programs
    If you want to use cstdio try it, it will either work or it won't
    All spelling mistakes, syntatical errors and stupid comments are intentional.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. realloc inside a routine
    By coletek in forum C Programming
    Replies: 4
    Last Post: 06-04-2009, 09:00 PM
  2. Replies: 3
    Last Post: 03-02-2008, 12:33 PM
  3. A small Debug routine
    By bftin in forum C++ Programming
    Replies: 1
    Last Post: 09-24-2004, 06:46 AM
  4. Running A Routine in the background
    By smegly in forum C Programming
    Replies: 4
    Last Post: 05-16-2004, 06:42 PM
  5. Linking an assembly routine into a GCC project
    By huh in forum C++ Programming
    Replies: 3
    Last Post: 11-21-2002, 03:14 PM