2

I have the following code:

 int a = 50;
 float b = 50.60f;

 a = int.Parse(b.ToString());

On run time this parsing gives as error. Why it is please guide me.

Thanks

2
  • 1
    a float is not an int. Furthermore, this code doesn't make much sense. If you want to get rid of the decimals, use a = (int)b. Commented Feb 1, 2012 at 9:30
  • Can you explain What you are trying it to achieve here? Commented Feb 1, 2012 at 9:31

5 Answers 5

5

It's trying to parse the string "50.6" - that can't be parsed as an integer, because 50.6 isn't an integer. From the documentation:

The s parameter contains a number of the form:

[ws][sign]digits[ws]

Perhaps you want to parse it back as a float and then cast to an integer?

a = (int) float.Parse(b.ToString());
Sign up to request clarification or add additional context in comments.

Comments

4

This is because int.Parse throws NumberFormatException if the string does not contain a parsable integer; 50.6 is not a prasable integer.

Comments

2

You are trying to parse a string that does not represent an integer into an integer.

This is why you are getting an exception.

Comments

2

It gives an error because you are trying to parse as int a string representing a float.

float b = 50.60f; // b = 50.6
                  // b.ToString() = "50.6" or "50,6" depending on locale
                  // int.Parse("50.6") MUST give an error because "50.6" is
                  // not a string representation of an integer

What is it that you want to do? Convert a float to an int? Just do this:

float b = 50.6f;
int a = (int)b;

That will truncate the value of b to simply 50.

Or do you want it rounded off to the nearest integer?

int a = (int)Math.Round(b);

Comments

1

Is the error message not specific enough?

Input string was not in a correct format.

int.Parse must take a string which can be parsed to an integer. The string "50.6" does not fulfil that requirement!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.