You are not logged in. Please login at to post your questions!


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.

asked 20 Apr, 22:21

mkbod's gravatar image

accept rate: 50%

edited 20 Apr, 22:24

What if the number if greater than 99999??

(20 Apr, 22:28) mathecodician6★

For now i'm assuming 5 digit number.

(20 Apr, 22:32) mkbod0★

Answer is hidden as author is suspended. Click here to view.

answered 20 Apr, 22:43

marshal_roxx's gravatar image

accept rate: 2%

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

(20 Apr, 22:47) abhi_shakes0★

floating point %05.4f will not work there!

(21 Apr, 00:37) bansal12324★

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


answered 21 Apr, 03:05

thinkinfinit's gravatar image

accept rate: 0%

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; 
    len = 0;
    x = n
    while (x >= 1){
        x /= 10;
        len += 1;
    for (int i = 0; i < 5-len; i++){
        cout << "0";
    cout << n << endl;

answered 20 Apr, 22:40

mathecodician's gravatar image

accept rate: 8%

edited 20 Apr, 22:41

Here is the code that you are asking: Ideone

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


answered 20 Apr, 23:59

bansal1232's gravatar image

accept rate: 16%

edited 21 Apr, 00:00

The question can also be solved using strings. Here's the code:


answered 21 Apr, 01:24

ayan_nitd's gravatar image

accept rate: 6%

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 20 Apr, 22:21

question was seen: 326 times

last updated: 21 Apr, 03:05