ภาพรวม
เพื่อแปลงค่า double เป็น int (Int32) ให้ใช้เมธอด Convert.ToInt32() ซึ่งจะ ปัดเศษทศนิยม ตามกฎ Banker's Rounding (ปัดเป็นเลขคู่เมื่ออยู่กึ่งกลาง)
รูปแบบการใช้งาน
double val = 21.34; int res = Convert.ToInt32(val); // 21
ตัวอย่างโค้ดเต็ม
using System;
public class Demo
{
public static void Main()
{
double val = 21.34;
int res = Convert.ToInt32(val);
Console.WriteLine("Converted double {0} to integer {1}", val, res);
}
}
ผลลัพธ์
Converted double 21.34 to integer 21
เมธอดแปลงที่เกี่ยวข้อง
| เมธอด | พฤติกรรม | ตัวอย่าง 21.5 | ตัวอย่าง -21.5 |
|---|---|---|---|
Convert.ToInt32 | ปัด Banker's Rounding | 22 | -22 |
(int)val (cast) | ตัดทศนิยม (truncate) | 21 | -21 |
Math.Round | ปัดตามกฎที่ระบุ | 22 (default) | -22 |
Math.Floor | ปัดลง | 21 | -22 |
Math.Ceiling | ปัดขึ้น | 22 | -21 |
Math.Truncate | ตัดทศนิยม | 21 | -21 |