Shinji
Shinji

Reputation: 85

Convert.ToInt32 does not take the a zero ( 0 ) as a starting integer

I have a question or actually two regarding the Convert.ToInt32 function or Int32.Parse.

It seems when I use Int32.Parse("06487965") or the other function it just seems to lose the 0. So the output will be "6487965".

My questions:

  1. Why is that exactly ?
  2. How can I solve this without getting into crazy hacks ?

Upvotes: 0

Views: 4838

Answers (7)

sasjaq
sasjaq

Reputation: 771

because, nobody uses pading, here is it:

int intValue =  Int32.Parse("06487965");
string stringAgain = intValue.ToString().PadLeft(9, '0');

Upvotes: 0

Nigel Harper
Nigel Harper

Reputation: 1250

Leading zeroes are meaningless when converting to a numeric type like Int32 - it only cares about the actual numeric value represented by the string you're converting from, which is the same regardless of the number of zeroes stuck on the front.

If later on in your program you want to convert your Int32 back to a string or output it to your user then at that point you need to do some formatting to get the number of leading zeroes you want. The MSDN article "How to: Pad a Number with Leading Zeros" would be a good place to start with that.

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38820

Leading-zeroes are purely a formatting idiom. An actual number has no leading zeroes as they make no sense and are superfluous.

You don't really have anything to solve, BUT, if you want to display the number at a later point with a leading zero, then you can use string formatting to achieve this.

int myNum = 6487965;
string formatted = string.Format("{0:00000000}", myNum);

Upvotes: 5

user448516
user448516

Reputation:

integer 06487965 equals to integer 6487965

Upvotes: 0

Saeb Amini
Saeb Amini

Reputation: 24419

  1. Leading zeroes do not make sense mathematically

  2. You can't have leading zeroes in an integer, if you must have leading zeroes best way is to keep your variable as string.

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190976

Leading 0's aren't represented when you ToString an int by default. You want to pass a format like "00000000".

int value =  Int32.Parse("06487965");
string stringAgain = value.ToString("000000000");

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45058

Because in that form, the leading 0, or 0s is/are nonsensical and redundant.

It can become useful in terms of formatting, for visual representation when you know how it should be formatted, but otherwise it is a non-issue.

Upvotes: 2

Related Questions