Taylor Leese
Taylor Leese

Reputation: 52390

int.Parse() with leading zeros

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

Upvotes: 19

Views: 38349

Answers (8)

antonio
antonio

Reputation: 11130

For a decimal number:

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

For a 16 bit numbers, where leading zeros are common:

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

Upvotes: 1

David.Chu.ca
David.Chu.ca

Reputation: 38664

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.

Upvotes: 1

Wim
Wim

Reputation: 12092

Try

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.

Upvotes: 1

Michael Petrotta
Michael Petrotta

Reputation: 60942

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:

Upvotes: 27

Nick Berardi
Nick Berardi

Reputation: 54864

Try

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

Upvotes: 9

Guffa
Guffa

Reputation: 700572

You don't have to do anything at all. Adding leading zeroes does not cause a 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.

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.

Upvotes: 1

John Rayner
John Rayner

Reputation: 3535

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

Upvotes: 8

johnc
johnc

Reputation: 40223

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

Converts the string representation of a number to its 32-bit signed integer equivalent. 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);
      }

}

Upvotes: 4

Related Questions