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

Chuyển đổi Decimal sang UInt32 (32-bit unsigned integer) trong C#

Mục đích

Phương thức Decimal.ToUInt32(Decimal value) chuyển Decimal sang uint (UInt32). Phần thập phân bị cắt bỏ. Phạm vi hợp lệ: 0 đến 4.294.967.295.

Ví dụ 1: Decimal nhỏ hơn 1

using System;

public class Demo
{
    public static void Main()
    {
        decimal val = 0.001m;
        Console.WriteLine($"Decimal: {val}");

        uint res = Decimal.ToUInt32(val);
        Console.WriteLine($"UInt32: {res}");
    }
}

Kết quả

Decimal: 0.001
UInt32: 0

Ví dụ 2: Decimal có phần nguyên

using System;

public class Demo
{
    public static void Main()
    {
        decimal val = 67.487m;
        Console.WriteLine($"Decimal: {val}");

        uint res = Decimal.ToUInt32(val);
        Console.WriteLine($"UInt32: {res}");
    }
}

Kết quả

Decimal: 67.487
UInt32: 67

Ví dụ 3: Xử lý OverflowException

using System;

public class Demo
{
    public static void Main()
    {
        decimal[] tests = { -10m, 4294967295m, 4294967296m }; // MaxValue và MaxValue+1

        foreach (decimal d in tests)
        {
            try
            {
                uint res = Decimal.ToUInt32(d);
                Console.WriteLine($"{d} -> {res}");
            }
            catch (OverflowException)
            {
                Console.WriteLine($"{d} -> OverflowException");
            }
        }
    }
}

Kết quả

-10 -> OverflowException
4294967295 -> 4294967295
4294967296 -> OverflowException

Tóm tắt

  • Cắt bỏ phần thập phân (truncation).
  • Ném OverflowException nếu giá trị < 0 hoặc > UInt32.MaxValue.
  • Tương tự có ToInt32, ToInt64, ToUInt64...