Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

แปลง Decimal เป็น Int64 (long) ใน C#

ใช้เมธอด Convert.ToInt64() เพื่อแปลงค่า decimal เป็น long (Int64) ค่าทศนิยมจะถูกปัดเศษเป็นจำนวนเต็มที่ใกล้ที่สุด (Banker's Rounding)

ตัวอย่าง

decimal d = 190.66m;
long res = Convert.ToInt64(d); // ผลลัพธ์ 191

ตัวอย่างโค้ดเต็ม

using System;

class Demo
{
    static void Main()
    {
        decimal d = 190.66m;
        long res = Convert.ToInt64(d);
        Console.WriteLine("แปลง Decimal '{0}' เป็น Int64: {1}", d, res);
    }
}

ผลลัพธ์

แปลง Decimal '190.66' เป็น Int64: 191

สังเกต: 190.66 ถูกปัดเป็น 191 (ปัดไปทางคู่ - Banker's Rounding) หากต้องการปัดทิ้งทศนิยมให้ใช้ decimal.Truncate() หรือ Math.Truncate()