You are not logged in. Please login at www.codechef.com 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

0★mkbod
563
accept rate: 50%

edited 20 Apr, 22:24

What if the number if greater than 99999??

(20 Apr, 22:28) mathecodician5★

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

3★marshal_roxx
(suspended)
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

link

answered 21 Apr, 03:05

thinkinfinit's gravatar image

1★thinkinfinit
672
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; 
}    
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;
}
link

answered 20 Apr, 22:40

mathecodician's gravatar image

5★mathecodician
2.5k319
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

link

answered 20 Apr, 23:59

bansal1232's gravatar image

4★bansal1232
2.6k110
accept rate: 16%

edited 21 Apr, 00:00

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

link

answered 21 Apr, 01:24

ayan_nitd's gravatar image

3★ayan_nitd
827
accept rate: 7%

toggle preview
Preview

Follow this question

By Email:

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

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "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:

×1,366
×30

question asked: 20 Apr, 22:21

question was seen: 265 times

last updated: 21 Apr, 03:05