Convert.ToInt32 - Save previous zero

I have numbers stored in the database, and some have zero as their first digit, since they should always be specific numbers of digits. I have a text box with this number typed into it, so I do Convert.ToInt32 (TextBox.Text), which removes the leading zero, if any. Does anyone have any ideas how I can keep zero or add it to the beginning after converting?

+6
c #
source share
5 answers

The only way to keep previous zeros is to not convert it to a number.

The number has no leading zeros, because it contains only the value, not a string representation of the value.

If you want to convert it to a number and then convert back to a string, recreating the previous zeros, you can use your own format:

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

Or for a dynamic number of digits:

 string formatted = number.ToString(new String('0', numberOfDigits)); 
+26
source share

If you need to keep the null plus, save the value as a string. Integers cannot store information about filled zeros, because they simply represent a number.

If you need to confirm the entered number, use Int32.TryParse or match the value with the regular expression character (for example, "^\d+$" ).

Edit: In response to Guffa, you can use "D" ( MSDN ) to format to a given number of characters (zero padding if necessary):

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

The way I did this is when the number is returned to the database instead of feeding int with string using myint.ToString("0000000") . With the number 0 is the total length of the filled number.

+2
source share

You must use the string format to store leading zero:

 int fooValue = Convert.ToInt32(TextBox.Text) //operations with foo Value string formatValue = fooValue.ToString("#0000"); 
0
source share

This should also work.

 123.ToString().PadLeft(5, '0'); // 00123 
0
source share

All Articles