Convert.ToInt32 - Keep Preceding Zero

The only way to keep the preceding zeroes is to not convert it to a number.

A number doesn't have any preceding zeroes as it only contains the value, not the string representation of the value.

If you want to convert it to a number and then convert it back to a string, recreating the preceding zeroes, you can use a custom format:

string formatted = number.ToString("00000");

Or for a dynamic number of digits:

string formatted = number.ToString(new String('0', numberOfDigits));

If you need to keep a padded zero, then keep the value as a String. Integers cannot keep information about padded zeros, since they simply represent a number.

If you need to validate the number entered, either use Int32.TryParse or match the value against a regular expression (like "^\d+$").

Edit: In addition to Guffa's answer, you can use "D" (docs) to format to a specified number of characters (with zero padding, if necessary):

string formatted = number.ToString("D5"); // 13 -> 00013

Tags:

C#