c# - 将 double 转换为整数

标签 c# .net casting type-conversion

double 转换为 int 的最佳方法是什么?是否应该使用强制转换?

最佳答案

如果你想要默认的截断到零行为,你可以使用强制转换。或者,您可能想使用 Math.CeilingMath.RoundMath.Floor 等 - 虽然之后您仍然需要进行转换.

不要忘记 int 的范围比 double 的范围小得多。如果值在未检查的上下文中超出 int 的范围,则从 doubleint 的转换不会抛出异常,而调用Convert.ToInt32(double) 将。如果值超出范围,则强制转换的结果(在未经检查的上下文中)显式未定义。

关于c# - 将 double 转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181942/

相关文章:

c# - 用 Linq 查询替换 for-switch 循环

c# - 为什么我不能显式地将 int 转换为字符串?

c# - 远程处理异常 : Object 'xxx.rem' has been disconnected or does not exist at the server

c# - URL 在 C# 中编码所有非字母数字

.net - "boxing"在 .NET 中如何工作?

c - 使用armcc时为"Error #119: cast to type <..> is not allowed"

c - 错误 : initialization makes pointer from integer without a cast

c# - 事件处理程序中的延迟初始化

c# - :disabled attribute on my button does not seem to work

c# - NServiceBus 在非侵入式模式下找不到 Endpoint 或 MessageEndpointMappings