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
int i = int.parse(value.TrimStart('0'));
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_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.
...and here's a report on Microsoft Connect about the issue: