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

การแปลง Decimal เป็นจำนวนเต็มไม่มีเครื่องหมาย 32 บิตใน C#

ภาพรวม

เมธอด Decimal.ToUInt32(Decimal) แปลง Decimal เป็น uint (32-bit unsigned integer) โดยตัดส่วนทศนิยม

ตัวอย่าง 1: ค่าทศนิยมน้อยกว่า 1

using System;

public class Demo {
    public static void Main() {
        Decimal val = 0.001m;
        Console.WriteLine("Decimal value = " + val);
        uint res = Decimal.ToUInt32(val);
        Console.WriteLine("32-bit unsigned integer = " + res);
    }
}

ผลลัพธ์ตัวอย่าง 1

Decimal value = 0.001
32-bit unsigned integer = 0

ตัวอย่าง 2: ค่าที่มีทศนิยม

using System;

public class Demo {
    public static void Main() {
        Decimal val = 67.487m;
        Console.WriteLine("Decimal value = " + val);
        uint res = Decimal.ToUInt32(val);
        Console.WriteLine("32-bit unsigned integer = " + res);
    }
}

ผลลัพธ์ตัวอย่าง 2

Decimal value = 67.487
32-bit unsigned integer = 67

สรุป

  • ตัดทศนิยมทิ้ง (truncate) ไม่ได้ปัดเศษ
  • โยน OverflowException หากค่าลบหรือเกิน 4,294,967,295
  • ใช้เมื่อต้องการแปลงเป็นจำนวนเต็มไม่มีเครื่องหมาย 32 บิต