This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

sprintf and justification\padding?

I'm trying to pad\justify my text such that everything aligns properly. Can I do this from within sprintf? I've tried all kinds of combinations within the format string.

Basically, this is the output I would like:

#001
#002
#003
....
#010
etc

unsigned char num;
unsigned char buf[20];

num = 0x01;

sprintf(&buf[0], "#%bU", num);

How can I pad the zeros in there?

Thanks
James

Parents
  • In "%4.1f", the numbers do not mean, as you might expect, "4 digits before the decimal, and 1 after". They mean "total field width of 4 characters, with 1 character after the decimal point." For your right-justified floats to line up, the total field width must be at least as large as the value you are trying to print. 2000.1, for example, is six characters wide. Larger values will overflow the field.

    So, you might try:

    "#%03u %6.1f"

    or, including the two spaces in the field width of the float

    "#%03u%8.1f"

    The "precision" field (the number after the decimal point) is irrelevant for integers.

Reply
  • In "%4.1f", the numbers do not mean, as you might expect, "4 digits before the decimal, and 1 after". They mean "total field width of 4 characters, with 1 character after the decimal point." For your right-justified floats to line up, the total field width must be at least as large as the value you are trying to print. 2000.1, for example, is six characters wide. Larger values will overflow the field.

    So, you might try:

    "#%03u %6.1f"

    or, including the two spaces in the field width of the float

    "#%03u%8.1f"

    The "precision" field (the number after the decimal point) is irrelevant for integers.

Children
No data