Converting string to int without losing the zero i

2019-03-26 14:44发布

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?

10条回答
SAY GOODBYE
2楼-- · 2019-03-26 14:50
// 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);
查看更多
Ridiculous、
3楼-- · 2019-03-26 14:53

Int values cannot have leading zeros

查看更多
迷人小祖宗
4楼-- · 2019-03-26 14:54

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();    
查看更多
何必那么认真
5楼-- · 2019-03-26 14:56
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.

查看更多
Juvenile、少年°
6楼-- · 2019-03-26 14:56

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.

查看更多
老娘就宠你
7楼-- · 2019-03-26 14:57

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.

查看更多
登录 后发表回答