int.Parse() with leading zeros

后端 未结 8 809
粉色の甜心
粉色の甜心 2020-12-11 01:38

How do I prevent the code below from throwing a FormatException. I\'d like to be able to parse strings with a leading zero into ints. Is there a clean way to do

相关标签:
8条回答
  • 2020-12-11 02:04

    Try

    int i = Int32.Parse(value, NumberStyles.Any);
    
    0 讨论(0)
  • 2020-12-11 02:04

    Try

    int i = Convert.ToInt32(value);

    Edit: Hmm. As pointed out, it's just wrapping Int32.Parse. Not sure why you're getting the FormatException, regardless.

    0 讨论(0)
  • 2020-12-11 02:12

    I have the following codes that may be helpful:

    int i = int.Parse(value.Trim().Length > 1 ?
        value.TrimStart(new char[] {'0'}) : value.Trim());
    

    This will trim off all extra leading 0s and avoid the case of only one 0.

    0 讨论(0)
  • 2020-12-11 02:13

    TryParse will allow you to confirm the result of the parse without throwing an exception. To quote MSDN

    Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

    To use their example

       private static void TryToParse(string value)
       {
          int number;
          bool result = Int32.TryParse(value, out number);
          if (result)
          {
             Console.WriteLine("Converted '{0}' to {1}.", value, number);         
          }
          else
          {
             if (value == null) value = ""; 
             Console.WriteLine("Attempted conversion of '{0}' failed.", value);
          }
    

    }

    0 讨论(0)
  • 2020-12-11 02:20

    You don't have to do anything at all. Adding leading zeroes does not cause a FormatException.

    To be 100% sure I tried your code, and after correcting parse to Parse it runs just fine and doesn't throw any exception.

    Obviously you are not showing actual code that you are using, so it's impossible to say where the problem is, but it's definitely not a problem for the Parse method to handle leading zeroes.

    0 讨论(0)
  • 2020-12-11 02:21

    For a decimal number:

    Convert.ToInt32("01", 10);
    // 1
    

    For a 16 bit numbers, where leading zeros are common:

    Convert.ToInt32("00000000ff", 16);
    // 255
    
    0 讨论(0)
提交回复
热议问题