我有一个double值,我想转换成Int32.如果可以转换,我如何在转换前检查?
有时值未定义,转换为Int32会抛出OverflowException.
我已经尝试过这样测试:
double value = getSomeValue();
if (value == Double.NAN) {
value =0;
}
int v = Convert.ToInt32(value);
Run Code Online (Sandbox Code Playgroud)
但这并未涵盖所有情况.
也许这个?
更新:我相信下面的更新解决了边缘情况.我已经针对每种情况对这种情况进行了测试,我可以考虑针对Convert.ToInt32直接尝试并捕获异常的方法验证输出.
static bool TryConvertToInt32(double value, out int result)
{
const double Min = int.MinValue - 0.5;
const double Max = int.MaxValue + 0.5;
// Notes:
// 1. double.IsNaN is needed for exclusion purposes because NaN compares
// false for <, >=, etc. for every value (including itself).
// 2. value < Min is correct because -2147483648.5 rounds to int.MinValue.
// 3. value >= Max is correct because 2147483648.5 rounds to int.MaxValue + 1.
if (double.IsNaN(value) || value < Min || value >= Max)
{
result = 0;
return false;
}
result = Convert.ToInt32(value);
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1531 次 |
| 最近记录: |