尝试将float转换为Int32时Convert.ToInt32(float)失败 [英] Convert.ToInt32(float) fails when trying to convert float to Int32

查看:380
本文介绍了尝试将float转换为Int32时Convert.ToInt32(float)失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不会引发任何异常,函数只会在以下语句处停止:

No exception is thrown, function just halts at this statement:

int productQuantity = Convert.ToInt32("1.00");

并返回.

将该浮点数转换为Int32时,我做错了什么?

What am I doing wrong to convert this float to Int32?

注意:我正在BackgroundWorkerThread中跑步.

推荐答案

在这种情况下,将引发异常,但它并未在调试器中浮出水面.此字符串的格式不能转换为Int32类型,因此会引发异常.如果IDE不合作,则可以通过将其包装在try/catch块中来进行验证.

An exception is being thrown in this case it's just not being surfaced in the debugger. This string is not in a format that is convertible to an Int32 type and hence throws and exception. You can verify this by wrapping it in a try/catch block if the IDE isn't cooperating.

这里最好的方法可能是将字符串转换为double,然后手动将其转换为int.由于精度差异,这确实为数据丢失打开了大门.但是鉴于您输入的内容为浮动样式格式,如果您希望最终产品为int

The best approach here is probably to convert the string to a double and then manually cast it down to an int. This does open the door for data loss due to precision differences. But given your input is in a float style format this is unavoidable if you want the final product to be an int

这篇关于尝试将float转换为Int32时Convert.ToInt32(float)失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆