decimal型 を long型 にキャストするには decimal.ToInt64() メソッドを使用します。
decimal型 を long型 に変換する方法
csharplong値 = decimal.ToInt64(decimal値);
VB.NET
Long値 = Decimal.ToInt64(Decimal値)
-
小数点以下は、 0 方向に最も近い整数値に丸められます
- 0.9 -> 0
- 5.1 -> 5
- -0.9 -> 0
- -5.1 -> -5
- 変換後の値がlongの範囲(-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807)を超える場合、例外(System.OverflowException)が発生します。
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以外のバージョンではプロジェクトを開いた際にファイルの変換が必要な場合があります。その場合は変換後に実行してください。検証環境
- Microsoft Visual Studio Professional 2017 Version 15.9.21
- Microsoft .NET Framework Version 4.6
- Microsoft Windows 10 Pro Version 1909 OS Build 18363.1016