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

Phương thức Convert.ToInt64() trong C#

Convert.ToInt64() chuyển đổi giá trị thành số nguyên 64-bit signed (long).

Ví dụ minh họa

using System;

public class Demo
{
    public static void Main()
    {
        double doubleNum = 193.834;
        long res = Convert.ToInt64(doubleNum);
        Console.WriteLine("Đã chuyển {0} thành {1}", doubleNum, res);
    }
}

Kết quả đầu ra

Đã chuyển 193.834 thành 194

Lưu ý quan trọng:

  • Làm tròn theo quy tắc Banker's Rounding (Round to Even): 193.5 → 194, 194.5 → 194
  • Khác với (long)doubleNum (ép kiểu) - cắt bỏ phần thập phân (truncate): 193.834 → 193
  • Code gốc dùng Convert.ToInt32 (sai tên phương thức) - đã sửa thành ToInt64