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
Try
int i = Int32.Parse(value, NumberStyles.Any);
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.
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.
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);
}
}
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.
For a decimal number:
Convert.ToInt32("01", 10);
// 1
For a 16 bit numbers, where leading zeros are common:
Convert.ToInt32("00000000ff", 16);
// 255