Best (safest) way to convert from double to int

前端 未结 8 1063
感情败类
感情败类 2021-01-07 21:00

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 wou

8条回答
  •  粉色の甜心
    2021-01-07 21:42

    I realize this is not quite what the OP was asking for, but this info could be handy.

    Here is a comparison (from http://www.dotnetspider.com/resources/1812-Difference-among-Int-Parse-Convert-ToInt.aspx)

            string s1 = "1234";
            string s2 = "1234.65";
            string s3 = null;
            string s4 = "12345678901234567890123456789012345678901234567890";
    
            int result;
            bool success;
    
            result = Int32.Parse(s1);      // 1234
            result = Int32.Parse(s2);      // FormatException
            result = Int32.Parse(s3);      // ArgumentNullException
            result = Int32.Parse(s4);      // OverflowException
    
            result = Convert.ToInt32(s1);      // 1234
            result = Convert.ToInt32(s2);      // FormatException
            result = Convert.ToInt32(s3);      // 0
            result = Convert.ToInt32(s4);      // OverflowException
    
            success = Int32.TryParse(s1, out result);      // 1234
            success = Int32.TryParse(s2, out result);      // 0
            success = Int32.TryParse(s3, out result);      // 0
            success = Int32.TryParse(s4, out result);      // 0
    

提交回复
热议问题