Converting string to int without losing the zero in the beginning

冷暖自知 提交于 2019-12-18 16:08:31

问题


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?


回答1:


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.




回答2:


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.




回答3:


If you want to do something like always print your number with 5 places, it goes like

myNumber.ToString().PadLeft(5, '0');



回答4:


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.




回答5:


you cannot. you will have to maintain the value as a string if you want it to remain that way.




回答6:


Int values cannot have leading zeros




回答7:


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.




回答8:


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.




回答9:


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



回答10:


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


来源:https://stackoverflow.com/questions/6615454/converting-string-to-int-without-losing-the-zero-in-the-beginning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!