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

【问题】

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

【解决过程】

1.参考:

去试了试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。

附:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值