Converting string to int without losing the zero in the beginning

后端 未结 10 459
Happy的楠姐
Happy的楠姐 2021-01-02 03:49

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.

相关标签:
10条回答
  • 2021-01-02 04:05
    // 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);
    
    0 讨论(0)
  • 2021-01-02 04:06

    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.

    0 讨论(0)
  • 2021-01-02 04: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();    
    
    0 讨论(0)
  • 2021-01-02 04:14

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

    0 讨论(0)
  • 2021-01-02 04:15

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

    myNumber.ToString().PadLeft(5, '0');
    
    0 讨论(0)
  • 2021-01-02 04:20

    Int values cannot have leading zeros

    0 讨论(0)
提交回复
热议问题