×

# printf with leading zeros in C

 1 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 0★mkbod 56●3 accept rate: 50% What if the number if greater than 99999?? (20 Apr, 22:28) For now i'm assuming 5 digit number. (20 Apr, 22:32) mkbod0★

 3 Answer is hidden as author is suspended. Click here to view. answered 20 Apr, 22:43 (suspended) accept rate: 2% okay ... yes you are talking about padding spaces with 0 ?? (20 Apr, 22:47) floating point %05.4f will not work there! (21 Apr, 00:37)
 1 guys, please upvote me. i am new here. nad not able to ask question answered 21 Apr, 03:05 67●2 accept rate: 0%
 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; }  answered 20 Apr, 22:40 2.5k●3●19 accept rate: 8%
 0 The question can also be solved using strings. Here's the code: http://ideone.com/Bs9UHy answered 21 Apr, 01:24 82●7 accept rate: 7%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• 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