Convert.ToInt32 - Keep Preceding Zero

c#

Solution

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));

Problem

I have numbers stored in a database, and some have a zero as their first digit as they always need to be a certain amout of digits. I have a text box that has this number typed into it, so i do a Convert.ToInt32(TextBox.Text), which removes the starting zero if it has one. Does anyone have any ideas how i can keep the zero, or add it to the start after the convert?

Original source