尝试将 float 转换为 Int32 时 Convert.ToInt32(float) 失败
没有抛出异常,函数只是在此语句处停止:
int productQuantity = Convert.ToInt32("1.00");
并返回。
将此浮点数转换为 Int32 时我做错了什么?
注意:我正在 BackgroundWorkerThread
中运行。
No exception is thrown, function just halts at this statement:
int productQuantity = Convert.ToInt32("1.00");
and returns.
What am I doing wrong to convert this float to Int32
?
Note: I am running in a BackgroundWorkerThread
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下会抛出异常,它只是没有在调试器中显示出来。该字符串的格式无法转换为
Int32
类型,因此会引发异常。如果 IDE 不配合,您可以通过将其包装在 try/catch 块中来验证这一点。这里最好的方法可能是将字符串转换为 double,然后手动将其转换为 int。这确实为由于精度差异而导致数据丢失打开了大门。但鉴于您的输入采用浮点样式格式,如果您希望最终产品为
int
,这是不可避免的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.The best approach here is probably to convert the string to a
double
and then manually cast it down to anint
. 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 anint
您需要先将其转换为
double
,然后再转换为Int32
。You need to convert it to a
double
first, and then convert toInt32
.抛出异常,只是要看到它,您必须检查
BackgroundWorker.RunWorkerCompleted
事件处理程序中的RunWorkerCompletedEventArgs.Error
属性。当后台工作完成时,从后台工作线程抛出的任何异常都会分配给该属性。
An exception is thrown, it's just that to see it you have to inspect the
RunWorkerCompletedEventArgs.Error
property in the event handler forBackgroundWorker.RunWorkerCompleted
.Any exception that is thrown from the background worker's thread when the background work is being done is assigned to that property.
格式异常
输入字符串的格式不正确。
FormatException
Input string was not in a correct format.