Convert.ToInt32 - Keep Preceding Zero
I have numbers stored in a database, and some have a zero as their first 开发者_StackOverflow社区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?
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
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.
This should also work.
123.ToString().PadLeft(5, '0'); // 00123
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");
精彩评论