Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int.Parse() with leading zeros

Tags:

c#

.net

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);
like image 612
Taylor Leese Avatar asked Nov 05 '09 00:11

Taylor Leese


People also ask

Does parseInt remove leading zeros?

Use parseInt() to remove leading zeros from a number in JavaScript.

Can an int have leading zeros?

You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. This article shows how to use both methods to pad a number with leading zeros.

What does int parse do?

Description. The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .


1 Answers

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:

like image 123
Michael Petrotta Avatar answered Sep 24 '22 08:09

Michael Petrotta