最新消息:20210917 已从crifan.com换到crifan.org

【已解决】C#中double/float转int,小数部分四舍五入

C# crifan 17154浏览 0评论

【问题】

C#中,需要将一个double的值转换为int类型。

【解决过程】

1.参考:

convert double to int

去试了试Math的Floor和Ceiling,已经Convert.Int64和Int32,测试结果见代码:

private void doubleToIntTest()
{
    double timeStampDouble = crl.getCurTimeInMillisec();    //1343403554609.3293

    Int64 timeStampInt64 = Convert.ToInt64(timeStampDouble);//1343403554609

    //An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll
    //Additional information: Value was either too large or too small for an Int32.
    //Int32 timeStampInt32 = Convert.ToInt32(timeStampDouble);

    int timeStampInt = (int)timeStampDouble;                //-2147483648

    double doubleFllor = Math.Floor(timeStampDouble);       //1343403554609.0
    double doubleCeiling = Math.Ceiling(timeStampDouble);   //1343403554610.0
    double doubleRound = Math.Round(timeStampDouble);       //1343403554609.0

    Int64 fllorInt64 = Convert.ToInt64(doubleFllor);        //1343403554609
    Int64 ceilingInt64 = Convert.ToInt64(doubleCeiling);    //1343403554610
    Int64 roundInt64 = Convert.ToInt64(doubleRound);        //1343403554609
}

【总结】

1. 想要将C#中的double变量转换为int变量,可以用:

当double的数值不大的话,用Convert.ToInt32,或直接用(int)强制转换也可以了,不过强制转换的时候,即使出错,也不报错的,所以如果遇到数据溢出等问题,强制转换的结果就是错的了。

当double的数值超过int32的话,用Conver.ToInt64。

2.想要获得对应的小数四舍五入的话,直接通过Math.Round即可,但是注意得到的结果仍是double。

 

附:

C#中double型如何转成int型,小数部分四舍五入到整数?

转载请注明:在路上 » 【已解决】C#中double/float转int,小数部分四舍五入

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.186 seconds, using 23.31MB memory