Thread: round up to x decimals in printf

  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,815
    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%.

    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.

  3. #3
    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,909
    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-16-2008, 12:56 AM
  4. How do I round decimals
    By fastlane29 in forum C++ Programming
    Replies: 5
    Last Post: 03-19-2002, 08:44 PM
  5. round and abs in c++
    By asimos in forum C++ Programming
    Replies: 6
    Last Post: 02-02-2002, 02:15 PM