简体   繁体   English

int.Parse()上的错误

[英]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. 它试图解析字符串“ 50.6”-不能将其解析为整数,因为50.6 不是整数。 From the documentation : 文档中

The s parameter contains a number of the form: s参数包含以下形式的数字:

 [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. 因为您正尝试将表示浮点数的字符串解析为int格式,所以会出现错误。

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 . 这会将b的值截短为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. int.Parse必须采用可以解析为整数的字符串。 The string "50.6" does not fulfil that requirement! 字符串“ 50.6”不满足该要求!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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