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?
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.
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.
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.
Use String.PadLeft like this:
var result = input.ToString().PadLeft(length, '0');
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With