简体   繁体   English

带有前导零的int.Parse()

[英]int.Parse() with leading zeros

How do I prevent the code below from throwing a FormatException . 如何防止下面的代码抛出FormatException I'd like to be able to parse strings with a leading zero into ints. 我希望能够将前导零的字符串解析为整数。 Is there a clean way to do this? 有干净的方法吗?

string value = "01";
int i = int.Parse(value);

Your code runs for me, without a FormatException (once you capitalize the method properly): 你的代码为我运行,没有FormatException (一旦你正确地利用了方法):

string value = "01";
int i = int.Parse(value);

But this does ring an old bell; 但这确实敲响了一个老钟; a problem I had years ago, which Microsoft accepted as a bug against localization components of Windows (not .NET). 我几年前遇到的一个问题,微软认为这是一个针对Windows(而不是.NET)本地化组件的错误。 To test whether you're seeing this, run this code and let us know whether you get a FormatException: 要测试您是否看到此内容,请运行此代码并告知我们您是否收到FormatException:

string value = "0"; // just a zero
int i = int.Parse(value);

EDIT : here's my post from Usenet, from back in 2007. See if the symptoms match yours. 编辑 :这是我在2007年从Usenet发布的帖子。看看症状是否与你的相符。

For reference, here's what we found. 作为参考,这是我们发现的。 The affected machine had bad data for the registry value [HKEY_CURRENT_USER\\Control Panel \\International\\sPositiveSign]. 受影响的计算机的注册表值[HKEY_CURRENT_USER \\ Control Panel \\ International \\ sPositiveSign]的数据不正确。 Normally, this value is an empty REG_SZ (null-terminated string). 通常,此值为空REG_SZ(以null结尾的字符串)。 In this case, the string was missing its terminator. 在这种情况下,字符串缺少其终结符。 This confused the API function GetLocaleInfoW(), causing it to think that '0' (ASCII number zero) was the positive sign for the current locale (it should normally be '+'). 这混淆了API函数GetLocaleInfoW(),导致它认为'0'(ASCII数字零)是当前语言环境的正号(通常应为'+')。 This caused all kinds of havoc. 这造成了各种各样的破坏。

You can verify this for yourself with regedit.exe: open that reg value by right-clicking on the value and selecting 'Modify Binary Data'. 您可以使用regedit.exe自行验证:通过右键单击该值并选择“修改二进制数据”来打开该值。 You should see two dots on the right (representing the null terminator). 您应该在右侧看到两个点(表示空终止符)。 If you see no dots, you're affected. 如果你看不到任何点,你就会受到影响。 Fix it by adding a terminator (four zeros). 通过添加终结符(四个零)来修复它。

You can also check the value of CultureInfo.CurrentCulture.NumberFormat.PositiveSign; 您还可以检查CultureInfo.CurrentCulture.NumberFormat.PositiveSign的值; it should be '+'. 它应该是'+'。

It's a bug in the Windows localization API, not the class libs. 这是Windows本地化API中的错误,而不是类库。 The reg value needs to be checked for a terminator. 需要检查reg值以获得终结符。 They're looking at it. 他们正在看着它。

...and here's a report on Microsoft Connect about the issue: ...以下有关此问题的Microsoft Connect报告

尝试

int i = Int32.Parse(value, NumberStyles.Any);
int i = int.parse(value.TrimStart('0'));

TryParse will allow you to confirm the result of the parse without throwing an exception. TryParse允许您在不抛出异常的情况下确认解析的结果。 To quote MSDN 引用MSDN

Converts the string representation of a number to its 32-bit signed integer equivalent. 将数字的字符串表示形式转换为其等效的32位有符号整数。 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);
      }

} }

Try 尝试

int i = Convert.ToInt32(value); int i = Convert.ToInt32(value);

Edit : Hmm. 编辑 :嗯。 As pointed out, it's just wrapping Int32.Parse. 正如所指出的,它只是包装Int32.Parse。 Not sure why you're getting the FormatException, regardless. 不知道为什么你得到FormatException。

You don't have to do anything at all. 你根本不需要做任何事情。 Adding leading zeroes does not cause a FormatException. 添加前导零不会导致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. 为了100%肯定我尝试了你的代码,并在纠正parseParse它运行得很好并且不会抛出任何异常。

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. 显然你没有显示你正在使用的实际代码,所以不可能说出问题出在哪里,但对于处理前导零的Parse方法来说绝对不是问题。

For a decimal number: 对于十进制数:

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

For a 16 bit numbers, where leading zeros are common: 对于16位数字,前导零是常见的:

Convert.ToInt32("00000000ff", 16);
// 255

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的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM