从double转换为int的最佳(最安全)方法 [英] Best (safest) way to convert from double to int

查看:436
本文介绍了从double转换为int的最佳(最安全)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对将双精度型转换为int的最佳方法感到好奇.在此,运行时安全是我的主要关注点(不一定是最快的方法,但这是我的次要关注点).我留下了一些我可以在下面提出的选择.任何人都可以权衡哪种最佳做法吗?没有列出的更好的方法来实现这一点?

I'm curious as to the best way to convert a double to an int. Runtime safety is my primary concern here (it doesn't necessarily have to be the fastest method, but that would be my secondary concern). I've left a few options I can come up with below. Can anyone weigh in on which is best practice? Any better ways to accomplish this that I haven't listed?

        double foo = 1;
        int bar;

        // Option 1
        bool parsed = Int32.TryParse(foo.ToString(), out bar);
        if (parsed)
        {
            //...
        }

        // Option 2
        bar = Convert.ToInt32(foo);

        // Option 3
        if (foo < Int32.MaxValue && foo > Int32.MinValue) { bar = (Int32)foo; }

推荐答案

我认为您最好的选择是:

I think your best option would be to do:

checked
{
    try
    {
        int bar = (int)foo;
    }
    catch (OverflowException)
    {
     ...          
    }
}

来自显式数值转换表

当您从double或float值转换为整数类型时, 该值将被截断.如果结果积分值在 目标值的范围,结果取决于溢出 检查上下文.在检查的上下文中,OverflowException是 在未经检查的上下文中抛出的结果是未指定的 目标类型的值.

When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

注意:选项2 还会在出现OverflowException时抛出OverflowException必填.

Note: Option 2 also throws an OverflowExceptionwhen required.

这篇关于从double转换为int的最佳(最安全)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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