Reputation: 85
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:
Upvotes: 0
Views: 4838
Reputation: 771
because, nobody uses pading, here is it:
int intValue = Int32.Parse("06487965");
string stringAgain = intValue.ToString().PadLeft(9, '0');
Upvotes: 0
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
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
Reputation: 24419
Leading zeroes do not make sense mathematically
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
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
Reputation: 45058
Because in that form, the leading 0
, or 0
s 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