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

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

ภาพรวม

Decimal.ToUInt16(Decimal value) แปลงค่า Decimal เป็น ushort (0 ถึง 65535) ตัดทศนิยมทิ้ง (truncate) โยน Exception หากเกินขอบเขต

ตัวอย่างที่ 1: แปลง 875.647 เป็น ushort

using System;

public class Demo
{
    public static void Main()
    {
        Decimal val = 875.647m;
        Console.WriteLine("Decimal value = " + val);

        ushort res = Decimal.ToUInt16(val);
        Console.WriteLine("16-bit unsigned integer = " + res);
    }
}

ผลลัพธ์

Decimal value = 875.647
16-bit unsigned integer = 875

ตัวอย่างที่ 2: แปลง 0.001 เป็น ushort (ค่าต่ำกว่า 1)

using System;

public class Demo
{
    public static void Main()
    {
        Decimal val = 0.001m;
        Console.WriteLine("Decimal value = " + val);

        ushort res = Decimal.ToUInt16(val);
        Console.WriteLine("16-bit unsigned integer = " + res);
    }
}

ผลลัพธ์

Decimal value = 0.001
16-bit unsigned integer = 0

สรุป

  • ตัดส่วนทศนิยมทิ้ง (ไม่ปัดเศษ)
  • ช่วงค่าที่รับได้: 0 ถึง 65,535
  • โยน OverflowException หากค่าติดลบหรือเกิน 65535
  • มีเมธอดคล้ายกัน: ToByte, ToUInt32, ToUInt64, ToInt16, ToInt32, ToInt64