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

Phương thức Decimal.ToInt32() trong C#


Phương thức Decimal.ToInt32() trong C# được sử dụng để chuyển đổi giá trị của Decimal được chỉ định thành số nguyên 32-bit có dấu tương đương.

Cú pháp

Dưới đây là cú pháp:

public static int ToInt32 (decimal val);

Trong đó, val là số thập phân cần chuyển đổi.

Ví dụ 1

Hãy xem ví dụ sau để triển khai phương thức Decimal.ToInt32():

using System;
public class Demo {
    public static void Main(){
        Decimal val1 = 0.001m;
        Decimal val2 = 1.000m;
        Console.WriteLine("Decimal 1 = " + val1);
        Console.WriteLine("Decimal 2 = " + val2);
        int res1 = Decimal.ToInt32(val1);
        int res2 = Decimal.ToInt32(val2);
        Console.WriteLine("32-bit signed integer (value1) (Decimal to signed integer) = " + res1);
        Console.WriteLine("32-bit signed integer (value2) (Decimal to signed integer) = " + res2);
    }
}

Đầu ra

Chương trình sẽ cho ra kết quả sau:

Decimal 1 = 0.001
Decimal 2 = 1.000
32-bit signed integer (value1) (Decimal to signed integer) = 0
32-bit signed integer (value2) (Decimal to signed integer) = 1

Ví dụ 2

Ví dụ khác triển khai phương thức Decimal.ToInt32() với số âm:

using System;
public class Demo {
    public static void Main(){
        Decimal val1 = -3.578m;
        Decimal val2 = 9.352m;
        Console.WriteLine("Decimal 1 = " + val1);
        Console.WriteLine("Decimal 2 = " + val2);
        int res1 = Decimal.ToInt32(val1);
        int res2 = Decimal.ToInt32(val2);
        Console.WriteLine("32-bit signed integer (value1) (Decimal to signed integer) = " + res1);
        Console.WriteLine("32-bit signed integer (value2) (Decimal to signed integer) = " + res2);
    }
}

Đầu ra

Chương trình sẽ cho ra kết quả sau:

Decimal 1 = -3.578
Decimal 2 = 9.352
32-bit signed integer (value1) (Decimal to signed integer) = -3
32-bit signed integer (value2) (Decimal to signed integer) = 9