Doruk
Doruk

Reputation: 914

Input string was not in correct format error when parsing to int

I get error "Input string was not in correct format" when parsing to int. But string is in correct format. I'm adding screenshot below.

enter image description here

Upvotes: 0

Views: 342

Answers (4)

Sandip Bantawa
Sandip Bantawa

Reputation: 2880

I think you are using REST API with JSON or passing whole string in query string i.e JSON formatted string, then you should use

a = new JavaScriptSerializer().Deserialize(a, null).ToString();
x = int.Parse(a);

Upvotes: 1

Jens Bornschein
Jens Bornschein

Reputation: 163

Maybe you can try something like this:

int x = Convert.ToInt32(a);

Furthermore you can try to use the .ToString() Methode of a to make it run more stable.


You can additionaly try to clear the string from all "non number" chars using Rexex:

/// <summary>
/// RegEx to extract all non numeric values.
/// </summary>
private static readonly Regex rxNonDigits = new Regex(@"[^\d.,-]+");

Use it as follows to clear:

String a2 = rxNonDigits.Replace(a, "");

Upvotes: 1

Pikoh
Pikoh

Reputation: 7703

The problem is that there must be some hidden characters in your a string variable (Carriage Return maybe?). Try int.Parse(a.Substring 0,4) as usually they are at the end of the string.

You could also clean the input where you are getting that value from.

Upvotes: 1

Morten Bork
Morten Bork

Reputation: 1632

I noticed you are doing multiple conversions. Are you sure it's a ("2016") that is causing the error? if yes, then there must be hidden characters as other have suggested. The a.substring(0,4) would indeed remove any trailing characters. But if the first character is a hidden char, it would not.

string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());

should clear out any possible hidden characters.

Upvotes: 1

Related Questions