Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToInt32 - Keep Preceding Zero

Tags:

c#

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?

like image 388
Grace Avatar asked Jan 11 '10 09:01

Grace


People also ask

How do you keep leading zeros in integers?

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.

Does convert ToInt32 round up or down?

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.

Does convert ToInt32 handle null?

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 .

Why do we use convert ToInt32?

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.


1 Answers

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));
like image 191
Guffa Avatar answered Oct 14 '22 08:10

Guffa