Converting string to int without losing the zero in the beginning

后端 未结 10 461
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:23

    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.

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

    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.

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

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

    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.

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