4

I would like to make the output of a number to always have 6 digits

e.g.:

  • if number is 1 the output should be 100000
  • if number is 23 the output should be 230000
  • if number is 236 the output should be 236000

How can I do this with printf/sprintf?

5 Answers 5

5

printf and its variants can pad zeroes to the left, not to the right. sprintf the number, then add the necessary zeros yourself, or make sure the number is 6 digits long:

while(num < 100000) 
    num *= 10;

(This code assumes the number isn't negative, or you're going to get in trouble)

Sign up to request clarification or add additional context in comments.

1 Comment

This is easily fixed: while ((num < 1000000) and (num > -1000000)), but much more importantly the number must be a 32bit integer or higher, a short or a char can't hold these kinds of values.
2

printf will return the number of character printed out. This you can print out the remaining zeros:

int num = 3; // init
int len = printf("%d", num);
for (int i = 0; i < 6-len; ++i)
    printf("0");

You should add some error checks (for example, if len is larger than 6).

With sprintf, you can use memset on the remaining buffer, which will be easier.

1 Comment

Rather than a loop, you could do if (len >= 0 && len < 6) printf("000000" + len);
1

You can't do it directly with printf (at least in a standard-conforming way), you need to alter your numbers beforehand.

Comments

0

Use the return value of printf (as in the first line of the for loop below)

#include <stdio.h>

int main(void) {
  int number, width = 6;
  for (number = 1; number < 9999999; number *= 7) {
    int digits = printf("%d", number);
    if (digits < width) printf("%0*d", width-digits, 0);
    puts("");
  }
  return 0;
}

See code running at http://ideone.com/TolIv

Comments

0

As Luchian said, this behavior is unsupported in printf, unlike the much more common reverse (left) padding. You could, however, easily enough generate the requested result with something like this:

char *number_to_six_digit_string(char *resulting_array, int number)
{
    int current_length = sprintf(resulting_array, "%d", number);
    while (6 > current_length) {
        resulting_array[current_length++] = '0';
    }
    resulting_array[current_length] = '\0';
    return resulting_array;
}

and then you could print the result:

char my_number[7];
printf("my number is %s, other stuff\n", number_to_six_digit_string(my_number, 13));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.