
[问题]
在C#中float 四舍五入,您需要将双精度值转换为int类型.
[解决过程]

1. 参考:
将double转换为int
我尝试过Math's 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)强制转换. 但是,即使在转换过程中发生错误,也不会报告任何错误,因此,如果您遇到数据溢出和其他问题float 四舍五入,则转换的结果是错误的.
当double的值超过int32时,请使用Conver.ToInt64.
2. 如果要获得相应的十进制舍入,只需传递Math.Round,但请注意结果仍然是两倍.

附加:
如何在C#中将double类型转换为int类型,将小数部分舍入为整数?
转载请注明: 在路上»[已解决] int in C#中的double / float int,四舍五入到小数部分
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-161117-1.html
怎么想都觉得可怕