尝试将 float 转换为 Int32 时 Convert.ToInt32(float) 失败

发布于 2024-09-15 10:34:00 字数 200 浏览 3 评论 0原文

没有抛出异常,函数只是在此语句处停止:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

带上头具痛哭 2024-09-22 10:34:00

在这种情况下会抛出异常,它只是没有在调试器中显示出来。该字符串的格式无法转换为 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 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

野却迷人 2024-09-22 10:34:00

您需要先将其转换为double,然后再转换为Int32

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

You need to convert it to a double first, and then convert to Int32.

int productQuantity = Convert.ToInt32(double.Parse("1.00"));
装纯掩盖桑 2024-09-22 10:34:00

抛出异常,只是要看到它,您必须检查 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 for BackgroundWorker.RunWorkerCompleted.

Any exception that is thrown from the background worker's thread when the background work is being done is assigned to that property.

音栖息无 2024-09-22 10:34:00

格式异常
输入字符串的格式不正确。

FormatException
Input string was not in a correct format.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文