0

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

13
  • Is something really wrong here or did my vacation time come ? Commented May 16, 2017 at 11:09
  • 3
    Looks fine. There might be some unprintable characters in the string which cause problems. Can you try to create a minimal reproducible example? Commented May 16, 2017 at 11:09
  • 1
    As @Heinzi said, there must be some hidden characters in your string. Try int.Parse(a.Substring 0,4) Commented May 16, 2017 at 11:10
  • 1
    What is a.Length? It must be more than 4. Commented May 16, 2017 at 11:14
  • 1
    @Doruk yes, but as Heinzi explained that would fail if you get a string without that leading character. It's better to clean the string as you now are doing. Glad it works Commented May 16, 2017 at 11:27

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

yeah. i'm sure.
did you try to clean up a with the line I suggested?
1

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

2 Comments

What difference do you expect between int.Parse and Convert.ToIn32?
I've added another idea for a “String” clearing method underneath.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.