Grace
Grace

Reputation: 2588

Convert.ToInt32 - Keep Preceding Zero

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?

Upvotes: 10

Views: 21947

Answers (5)

Richard Szalay
Richard Szalay

Reputation: 84784

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

Upvotes: 12

Manish Basantani
Manish Basantani

Reputation: 17509

This should also work.

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

Upvotes: 1

Andrew Cox
Andrew Cox

Reputation: 10988

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.

Upvotes: 2

elCairo
elCairo

Reputation: 81

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");

Upvotes: 0

Guffa
Guffa

Reputation: 700572

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));

Upvotes: 32

Related Questions