[C#][VB.NET]decimal型 を int型 に変換する(少数部を切り捨て)

decimal型 を int型 にキャストするには decimal.ToInt32() メソッドを使用します。

decimal型 を int型 に変換する方法

csharp
int値 = decimal.ToInt32(decimal値);

VB.NET

Integer値 = Decimal.ToInt32(decimal値)

C# サンプルコード

decimal decimalValue = 5.1M;

// decimal型 -> int型(少数は切り捨てされる)
int intValue = decimal.ToInt32(decimalValue);

// 結果は 5
Console.WriteLine(intValue);

桁あふれする場合

try
{
    // 桁あふれする場合
    decimal decimalValue = 2147483647M + 1;

    // 例外(System.OverflowException)が発生する
    int intValue = decimal.ToInt32(decimalValue);
}
catch (Exception ex)
{
    // 結果 -> System.OverflowException
    Console.WriteLine(ex.GetType());

    // 結果 -> Int32 型の値が大きすぎるか、または小さすぎます。
    Console.WriteLine(ex.Message);
}

VB.NET サンプルコード

Dim decimalValue As Decimal = 5.1

'Decimal型 -> Integer型(少数は切り捨てされる)
Dim intValue As Integer = Decimal.ToInt32(decimalValue)

'結果は 5
Console.WriteLine(intValue)

桁あふれする場合

Try
    '桁あふれする場合
    Dim decimalValue As Decimal = 2147483647D + 1D

    '例外(System.OverflowException)が発生する
    Dim intValue As Integer = Decimal.ToInt32(decimalValue)
Catch ex As Exception
    '結果 -> System.OverflowException
    Console.WriteLine(ex.GetType())

    '結果 -> Int32 型の値が大きすぎるか、または小さすぎます。
    Console.WriteLine(ex.Message)
End Try

関連記事

サンプルコードのダウンロード

サンプルコードの実行には Microsoft Visual Studio 2015 以上のバージョンが必要です。 2015以外のバージョンではプロジェクトを開いた際にファイルの変換が必要な場合があります。その場合は変換後に実行してください。

検証環境

関連ページ