代碼如下:
double mydouble = 85.63;
int myint = Convert.ToInt32(mydouble);
// 結果 myint == 86,而非預期的 85
Convert.ToInt32() 採用「四捨五入」規則(銀行家圓整法,即 .5 向最近的偶數進位),因此 85.63 四捨五入為 86。
而 (int) 強制轉換 或 Math.Truncate() 則是直接截取整數部分,忽略小數,結果為 85。
double d = 85.63;
Console.WriteLine(Convert.ToInt32(d)); // 86
Console.WriteLine((int)d); // 85
Console.WriteLine(Math.Truncate(d)); // 85
Console.WriteLine(Math.Floor(d)); // 85
Console.WriteLine(Math.Round(d)); // 86(四捨五入)
理解各轉換方法的語義差異,能避免數據處理中的隱性 Bug。