开发者

Converting string to int without losing the zero in the beginning

开发者 https://www.devze.com 2023-03-19 03:46 出处:网络
I tried 开发者_如何学JAVAint.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.

I tried 开发者_如何学JAVAint.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?


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.


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.


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

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


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.


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


Int values cannot have leading zeros


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.


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.


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


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


I had same problem; Solved it with an if else Couldn't find another solution for it

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号