2

In php I could do something like this:

if (balance == 0 && !neverBought)

Where balance comes from an API and is a string.

In C# I tried to convert balance to int as shown below:

if (int.Parse(balance) == 0 && !(neverBought))

But I get Exception Details: System.FormatException: Input string was not in a correct format.

What am I doing wrong?

Mansfield
  • 14,445
  • 18
  • 76
  • 112
mgiota
  • 203
  • 1
  • 4
  • 13

2 Answers2

7

If you are not sure if the string is valid use a method such as TryParse to attempt to parse it without throwing an exception:

Based on comments you also don't have an integer, you have a decimal value, so you should parse it as one as well.

decimal decimalBalance;
if(decimal .TryParse(balance, out decimalBalance) 
    && decimalBalance == 0m && !neverBought)
Servy
  • 202,030
  • 26
  • 332
  • 449
  • The approach suggested by @Servy is absolutely correct. You SHOULD use TryParse if you are uncertain of your input. However, I suspect you are suffering from the input string not being a number because coming from PHP, you are probably passing in some value like "$1,999.99" or similar where the '$' or the ',' are causing the problem. I think you need a "RemoveNonNumeric(this string s)" extension method. The basic approach with a Regex is discussed here: http://stackoverflow.com/questions/3055742/regex-to-remove-all-non-numeric-or-period – bopapa_1979 Oct 23 '13 at 20:03
  • @Eric You can simply provide an appropriate formatter to the third parameter of `TryParse`, based on one of the common formats, rather than using regexes which are generally rather fragile and harder to ensure the correctness of. – Servy Oct 23 '13 at 20:04
  • @Servy - I was unaware of this, so you got me curious. I'm providing a link to the docs/example for that overload just as a quick reference for anybody else that wants an easy look. MSDN:http://msdn.microsoft.com/EN-US/library/ew0seb73.aspx. On cool thing I noticed is that it also includes a NumberStyles flags parameter that can allow currency characters WIHTOUT any need to strip them. Slick! Thanks for pointing that out. You're also correct about the Regex. Very culture specific. For example, in some cultures 1.345,978 should parse to the decimal 1345.978. – bopapa_1979 Oct 23 '13 at 20:16
-1

Convert.ToInt32() would probaly help aswell if you are sure balance isn't a string

            string a = "3";
            int b = 3;
            if (Convert.ToInt32(a) == b)
            {
                //do smth
            }
Helmer
  • 116
  • 2