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?
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.
Round method. Of course Convert. ToInt32() does use this method already with the behavior described. It has to do with averages, you convert and add 6 numbers and half of them are rounded down and the other half are roudned up you get a more accurate number then if everything was rounded up or rounded down.
ToInt32(string s) method converts the string to integer. If string s is null , then it will return 0 rather than throw ArgumentNullException . If string s is other than integer value, then it will throw FormatException .
ToInt32(String, IFormatProvider) Method. This method is used to converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With