Decimal.Subtract() 方法在 C# 中
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
广告