C#中的Decimal.Subtract()方法
C#中的Decimal.Subtract()方法用于减去两个指定的Decimal值。
语法
以下是语法-
public static decimal Subtract (decimal val1, decimal val2);
在上面,va1是被减数,而val2是次变数。
示例
现在让我们看一个实现Decimal.Subtract()方法的示例-
using System; public class Demo { public static void Main(){ Decimal val1 = 3.45m; Decimal val2 = 2.35m; Console.WriteLine("Decimal 1 = "+val1); Console.WriteLine("Decimal 2 = "+val2); Decimal res = Decimal.Subtract(val1, val2); Console.WriteLine("Result (Subtract) = "+res); } }
输出结果
这将产生以下输出-
Decimal 1 = 3.45 Decimal 2 = 2.35 Result (Subtract) = 1.10
示例
现在让我们来看另一个实现Decimal.Subtract()方法的示例。由于值对于小数而言太大或太小,因此会显示错误-
using System; public class Demo { public static void Main(){ Decimal val1 = 2.35m; Decimal val2 = Decimal.MinValue; Console.WriteLine("Decimal 1 = "+val1); Console.WriteLine("Decimal 2 = "+val2); Decimal res = Decimal.Subtract(val1, val2); Console.WriteLine("Result (Subtract) = "+res); } }
输出结果
这将产生以下输出-
Decimal 1 = 2.35 Decimal 2 = -79228162514264337593543950335 Run-time exception (line 13): Value was either too large or too small for a Decimal. Stack Trace: [System.OverflowException: Value was either too large or too small for a Decimal.] at System.Decimal.FCallAddSub(Decimal& d1, Decimal& d2, Byte bSign) at System.Decimal.Subtract(Decimal d1, Decimal d2) at Demo.Main() :line 13