Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int (number) to string with leading zeros? (4 digits) [duplicate]

Tags:

c#

c#-4.0

Possible Duplicate:
Number formatting: how to convert 1 to "01", 2 to "02", etc.?

How can I convert int to string using the following scheme?

  • 1 converts to 0001
  • 123 converts to 0123

Of course, the length of the string is dynamic. For this sample, it is:

int length = 4; 

How can I convert like it?

like image 863
Ehsan Avatar asked Dec 11 '11 07:12

Ehsan


People also ask

How do you add leading zeros to numbers or text with uneven lengths JS?

To pad a number with leading zeros convert the number to a string and call the padStart() method. The padStart method allows you to add leading zeros to the start of the string until it reaches the specified target length.

Can an int have leading zeros?

You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. This article shows how to use both methods to pad a number with leading zeros.

How do you add leading zeros to a string in Python?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.


2 Answers

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0'); 
like image 178
Jens Avatar answered Oct 13 '22 03:10

Jens


Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4; int number = 50; string asString = number.ToString("D" + length); //"0050" 
like image 40
Jeff Mercado Avatar answered Oct 13 '22 02:10

Jeff Mercado