printf() formatting - stripping zeroes, padding

Discussion in 'C++' started by Piotr B., Oct 19, 2004.

  1. Piotr B.

    Piotr B. Guest

    Hello,

    Here are two questions on formatting values using printf():

    1. How to strip trailing zeroes from float values?
    printf("%f %f", 1.777, 1.2) displays "1.777000 1.200000",
    while I want to have "1.777 1.2", without loosing 6-digit
    precision.

    2. Is it possible to pad values with other characters than
    space and zero? printf(">%5s<", "abc") displays "> abc<".
    I would like to have e.g. ">##abc<" or ">--abc<".

    Thank you!
    Piotr B., Oct 19, 2004
    #1
    1. Advertising

  2. Piotr B. wrote:
    > Here are two questions on formatting values using printf():
    >
    > 1. How to strip trailing zeroes from float values?
    > printf("%f %f", 1.777, 1.2) displays "1.777000 1.200000",
    > while I want to have "1.777 1.2", without loosing 6-digit
    > precision.


    Use %g.

    > 2. Is it possible to pad values with other characters than
    > space and zero? printf(">%5s<", "abc") displays "> abc<".
    > I would like to have e.g. ">##abc<" or ">--abc<".


    Not for outputting strings. Create a temporary string and do
    your own padding.

    V
    Victor Bazarov, Oct 19, 2004
    #2
    1. Advertising

  3. Piotr B.

    CBFalconer Guest

    "Piotr B." wrote:
    >
    > 1. How to strip trailing zeroes from float values?
    > printf("%f %f", 1.777, 1.2) displays "1.777000 1.200000",
    > while I want to have "1.777 1.2", without loosing 6-digit
    > precision.


    printf("%.3f %.2f", 1.777, 1.2);

    Read the standard. Don't cross post between c.l.c and c.l.c++;
    they are different languages. Follow-ups set. c.l.c++ probably
    won't use printf anyhow.

    --
    "I support the Red Sox and any team that beats the Yankees"
    "Any baby snookums can be a Yankee fan, it takes real moral
    fiber to be a Red Sox fan"
    "I listened to Toronto come back from 3:0 in '42, I plan to
    watch Boston come back from 3:0 in 04"
    CBFalconer, Oct 19, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Michal Prinke
    Replies:
    0
    Views:
    329
    Michal Prinke
    Oct 19, 2004
  2. cjl
    Replies:
    11
    Views:
    809
    Bengt Richter
    Mar 26, 2005
  3. Michal Prinke

    printf() formatting - stripping zeroes, padding

    Michal Prinke, Oct 19, 2004, in forum: C Programming
    Replies:
    0
    Views:
    326
    Michal Prinke
    Oct 19, 2004
  4. Piotr B.
    Replies:
    4
    Views:
    651
    Piotr B.
    Oct 20, 2004
  5. pb
    Replies:
    15
    Views:
    11,164
    totoquebec
    Feb 6, 2012
Loading...

Share This Page