Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

string value = "01";
int i = int.Parse(value);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
664 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your code runs for me, without a FormatException (once you capitalize the method properly):

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:

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.

For reference, here's what we found. The affected machine had bad data for the registry value [HKEY_CURRENT_USERControl Panel InternationalsPositiveSign]. 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...