C# int.Parse() 带前导零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1677516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:55:01  来源:igfitidea点击:

int.Parse() with leading zeros

c#.net

提问by Taylor Leese

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 this?

如何防止下面的代码抛出FormatException. 我希望能够将带有前导零的字符串解析为整数。有没有干净的方法来做到这一点?

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

采纳答案by Michael Petrotta

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). To test whether you're seeing this, run this code and let us know whether you get a FormatException:

但这确实敲响了一个老钟;我多年前遇到的一个问题,Microsoft 将其视为针对 Windows(而非 .NET)本地化组件的错误。要测试您是否看到了这一点,请运行此代码并让我们知道您是否收到 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]. Normally, this value is an empty REG_SZ (null-terminated string). 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 '+'). 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'. 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; it should be '+'.

It's a bug in the Windows localization API, not the class libs. The reg value needs to be checked for a terminator. They're looking at it.

作为参考,这是我们发现的。受影响的计算机的注册表值 [HKEY_CURRENT_USER\Control Panel\International\sPositiveSign] 有错误的数据。通常,此值是一个空的 REG_SZ(以空字符结尾的字符串)。在这种情况下,字符串缺少终止符。这混淆了 API 函数 GetLocaleInfoW(),导致它认为“0”(ASCII 数字零)是当前语言环境的正号(通常应该是“+”)。这造成了各种破坏。

您可以使用 regedit.exe 自行验证这一点:通过右键单击该值并选择“修改二进制数据”来打开该 reg 值。您应该会在右侧看到两个点(代表空终止符)。如果你看不到点,你就会受到影响。通过添加终止符(四个零)来修复它。

您还可以检查 CultureInfo.CurrentCulture.NumberFormat.PositiveSign 的值;它应该是“+”。

这是 Windows 本地化 API 中的错误,而不是类库中的错误。需要检查 reg 值是否有终止符。他们在看。

...and here's a report on Microsoft Connectabout the issue:

...这是关于 Microsoft Connect 的关于该问题的报告

回答by Wim Hollebrandse

Try

尝试

int i = Convert.ToInt32(value);

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.

编辑:嗯。正如所指出的,它只是包装了 Int32.Parse。不知道为什么你会得到 FormatException,无论如何。

回答by johnc

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

TryParse将允许您在不抛出异常的情况下确认解析的结果。引用 MSDN

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

将数字的字符串表示形式转换为其等效的 32 位有符号整数。返回值指示操作是否成功。

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

}

}

回答by John Rayner

int i = int.parse(value.TrimStart('0'));

回答by Guffa

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 parseto Parseit runs just fine and doesn't throw any exception.

要100%地肯定我想你的代码,并修正后parse,以Parse它运行得很好,不会引发任何异常。

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 Parsemethod to handle leading zeroes.

显然,您没有显示您正在使用的实际代码,因此无法说明问题出在哪里,但是Parse对于处理前导零的方法来说绝对不是问题。

回答by Nick Berardi

Try

尝试

int i = Int32.Parse(value, NumberStyles.Any);

回答by David.Chu.ca

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

回答by antonio

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