C# Extension Method: Decimal - ToInt32

CSharp · Console

/Program.cs

// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002291/decimal-toint32

// @nuget: Z.ExtensionMethods

using System;
					
public class Program
{
	static string formatter = "{0,30}{1,23}";
	public static void Main()
	{
        decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 
                           123.999m, 4294967295.999m, 4294967296m,
                           4294967296m, 2147483647.999m, 2147483648m, 
                           -0.999m, -1m, -2147483648.999m, -2147483649m };
		
		Console.WriteLine(formatter, "Decimal value", "Int32");
        Console.WriteLine(formatter, "----------------", "------");

        foreach (var value in values)
        {
            try
            {
				// C# Extension Method: Decimal - ToInt32
                int number = value.ToInt32();
                Console.WriteLine(formatter, value, number);
            }
            catch (OverflowException e)
            {
                Console.WriteLine(formatter, e.GetType().Name, value);
            }
        }
	}
}
;