round up to x decimals in printf

This is a discussion on round up to x decimals in printf within the C Programming forums, part of the General Programming Boards category; Hello again ^^ Code: double rou=3.14195; printf("%f rounded = %.4f\n\n", rou, rou); output: 3.14195 rounded = 3.1420 Is it posible ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    14

    round up to x decimals in printf

    Hello again ^^


    Code:
    double rou=3.14195;
              printf("%f rounded = %.4f\n\n", rou, rou);
    output: 3.14195 rounded = 3.1420

    Is it posible for me to put a variable where the number 4 is?
    So I can round up to x decimals instead of a constant?

    Thanks for your time and help

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,425
    First create a format string using sprintf(). Then supply that format string to the printf() call.
    Right 98% of the time, and don't care about the other 3%.

  3. #3
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    try to put something like that in a function
    Code:
    int num_dec = 4;
    double rou=3.14195;
    char fmt[32];
    sprintf(fmt,"%f rounded = %%0.%df\n\n", rou,num_dec);
    printf(fmt, rou);
    Kurt

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,555
    You can put an * in the format specifier:
    Code:
    printf("%f rounded to %d places is %.*f\n", rou, num_dec, num_dec, rou);
    That * in blue means that you are going to pass the precision for the %f as the next parameter to printf.

  5. #5
    Registered User
    Join Date
    Mar 2012
    Posts
    14
    Thank you for your quick replies!
    Really appreciate it!
    Used andurils462 method at the end.
    Solved my problem.

    Thanks again for your time and help!

    Lolo

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. (Community Game) Round Robin for C++ [Round 01]
    By phantomotap in forum General Discussions
    Replies: 5
    Last Post: 04-18-2011, 01:07 PM
  2. (Community Game) Planning for Round Robin for C++ [Round 02]
    By phantomotap in forum General Discussions
    Replies: 2
    Last Post: 04-17-2011, 02:39 PM
  3. how to round-off decimals?
    By Marrah_janine in forum C# Programming
    Replies: 3
    Last Post: 02-15-2008, 11:56 PM
  4. How do I round decimals
    By fastlane29 in forum C++ Programming
    Replies: 5
    Last Post: 03-19-2002, 07:44 PM
  5. round and abs in c++
    By asimos in forum C++ Programming
    Replies: 6
    Last Post: 02-02-2002, 01:15 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21