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

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

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

csharp
long値 = decimal.ToInt64(decimal値);

VB.NET

Long値 = Decimal.ToInt64(Decimal値)

C# サンプルコード

decimal decimalValue = 5.1M;

// decimal型 -> long型(少数は切り捨てされる)
long longValue = decimal.ToInt64(decimalValue);

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

桁あふれする場合

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

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

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

VB.NET サンプルコード

Dim decimalValue As Decimal = 5.1

'Decimal型 -> Long型(少数は切り捨てされる)
Dim longValue As Long = Decimal.ToInt64(decimalValue)

'結果は 5
Console.WriteLine(longValue)

桁あふれする場合

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

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

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

関連記事

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

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

検証環境

関連ページ