Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer formatting, padding to a given length

I need to pad the output of an integer to a given length.

For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?

like image 951
Jring Qin Avatar asked Oct 13 '08 02:10

Jring Qin


People also ask

What is padding a number?

To pad a numeric value with leading zeros to a specific length. Determine how many digits to the left of the decimal you want the string representation of the number to have. Include any leading zeros in this total number of digits.

How do you add padding to a string in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How do I fill a string with 0?

Python String zfill() MethodThe zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.


1 Answers

Use the string.Format command.

output = String.Format("{0:0000}", intVariable); 

More details: http://msdn.microsoft.com/en-us/library/fht0f5be.aspx

like image 149
Stephen Wrighton Avatar answered Oct 21 '22 14:10

Stephen Wrighton