简体   繁体   中英

error on int.Parse()

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

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

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

This is why you are getting an exception.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM