tags:

views:

265

answers:

5

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?

+7  A: 

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" (MSDN) to format to a specified number of characters (with zero padding, if necessary):

string formatted = number.ToString("D5"); // 13 -> 00013
Richard Szalay
+1, for hinting about the Decimal ("D") format specifier. Since the question specifies `Convert.ToInt32()`, this is my personal preferred method of padding the value.
Codesleuth
+14  A: 

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));
Guffa
+1 for explaining both options, because the best solution depends on the nature of the data (imo)
Thorarin
Isn't `number.ToString().PadLeft(numberOfDigits, '0')` easier? At least easier to read I would say... :)
Svish
I'm worried about negative values when doing padding like this. Example, your PadLeft option would look like this: "00-9" instead of -009.
Codesleuth
A: 

You must use the string format for keep the leading zero:

int fooValue = Convert.ToInt32(TextBox.Text)
//operations with foo Value
string formatValue = fooValue.ToString("#0000");
elCairo
+1  A: 

The way I would do it is when the number is put back into the database instead of feeding it an int use a string by using myint.ToString("0000000"). With the number of 0's being the total length of the padded number.

Andrew Cox
A: 

This should also work.

123.ToString().PadLeft(5, '0'); // 00123
Amby
As commented on Svish's comment, this would create strange results with negative integers.
Codesleuth