printf with leading zeros in C

Let’s say I have a floating point number or an integer number, I want to print it in always 5 characters.

See, if output by the compiler is 21 then it should print 00021,

In case of 123, output should be 00123,

In case of 3.45, output should be 00003.45.

And now at the end, can you also help me to get alternative of zeros here in this case. I’m mean “printf with leading any character including zeros”?

For above case: x(any chaeacter)

1st output should be xxx21,
2nd output should be xx123,
3rd output should be xxxx3.45.

I hope you got the question.

1 Like

So first we need to calculate the number of digits before the decimal point.

Code -

n is the number
if (n < 1){
    cout << "0000" << n << endl; 
}    
else{       
    len = 0;
    x = n
    while (x >= 1){
        x /= 10;
        len += 1;
    }
    for (int i = 0; i < 5-len; i++){
        cout << "0";
    }
    cout << n << endl;
}

printf allows some formatting options.
example :-
printf(“leading zeros %05d”, 123);
this will print 5 digits with leading zeroes . Similar way for floating point %05.4f

3 Likes

Here is the code that you are asking: Ideone

To know more about printf() format specifier. Click here

The question can also be solved using strings. Here’s the code: http://ideone.com/Bs9UHy

guys, please upvote me. i am new here. nad not able to ask question

1 Like

What if the number if greater than 99999??

For now i’m assuming 5 digit number.

okay … yes you are talking about padding spaces with 0 ??

floating point %05.4f will not work there!