Reputation: 55022
I tried int.parse,
and convert class to convert a string to int.
While I'm converting. I'm losing the 0 in the beginning which i don't want.
Ex : 09999 becomes 9999 - I don't want this.
I want to keep it as it is.
How can i do that?
Upvotes: 17
Views: 37782
Reputation: 1
I had same problem; Solved it with an if else Couldn't find another solution for it
Upvotes: 0
Reputation: 6514
Although this is a old thread, but this can also help:
// convert to big integer
var bigIntBits = BigInteger.Parse(intNumber);
int indexOfOne = intNumber.IndexOf('1');
string backToString = new string('0', indexOfOne) + bigIntBits.ToString();
Upvotes: 0
Reputation: 31
// For our requirement that new ID's should be of same length as old ID's.
string strID = "002017";
int number = int.Parse(strID);
string newID = (++number).ToString("D" + strID.Length);
Upvotes: 1
Reputation: 391
myNumber.ToString("D5");
//D
represents 'Decimal', and 5 is the specified amount of digits you want the number to be always. This will pad your value with zeroes until it reaches 5 digits.
Upvotes: 39
Reputation: 354
you cant, but if you need to cast it to int and keep the zeros you can create a copy of it and then cast it to int, then you will have two versions of it one as int and one as string.
Upvotes: 0
Reputation: 1088
If you are just converting to int to test the value, keep the original data around and use the string value of it when you want the leading zeor. If you require the integer to have zero padding after mathematically working with it you will have to format it with sprintf or the like whenever you output it.
Upvotes: 0
Reputation: 11238
If you want to do something like always print your number with 5 places, it goes like
myNumber.ToString().PadLeft(5, '0');
Upvotes: 10
Reputation: 283614
No, int.Parse("09999")
actually returns 0x0000270F. Exactly 32 bits (because that's how big int
is), 18 of which are leading zeros (to be precise, one is a sign bit, you could argue there are only 17 leading zeros).
It's only when you convert it back to a string that you get "9999", presence or absence of the leading zero in said string is controlled by the conversion back to string.
Upvotes: 4
Reputation: 11744
You cannot. An int
is meant to represent a mathematical integer. The numbers 09999
and 9999
are exactly the same number, mathematically.
Perhaps there is a different problem here. Why do you need to do this? Maybe there's a better way to do what you want to do.
Upvotes: 16
Reputation: 318
you cannot. you will have to maintain the value as a string if you want it to remain that way.
Upvotes: 0