Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Convert.ToInt32() chuyển double sang int C#

Convert.ToInt32(double) chuyển double sang int với làm tròn Banker's Rounding (Round to Even).

Ví dụ minh họa

using System;

public class Demo
{
    public static void Main()
    {
        double doubleNum = 11.53;
        int intNum = Convert.ToInt32(doubleNum);
        Console.WriteLine("Đã chuyển {0} thành {1}", doubleNum, intNum);
    }
}

Kết quả đầu ra

Đã chuyển 11.53 thành 12

Lưu ý:

  • 11.53 → 12 (làm tròn)
  • Ép kiểu (int)11.53 → 11 (cắt bỏ phần thập phân)
  • 11.5 → 12, 12.5 → 12 (Banker's Rounding: số chẵn)

Lỗi code gốc: ntNum typo → đã sửa intNum.