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