當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Decimal.Subtract()用法及代碼示例


此方法用於從另一個減去一個指定的十進製值。

用法: public static decimal Subtract (decimal a1, decimal a2);

參數:
a1:此參數指定被減數。
a2:此參數指定替換。


返回值:從a1減去a2的結果。

異常:如果返回值小於MinValue或大於MaxValue,則此方法將給出OverflowException。

以下示例程序旨在說明上述方法的用法:

示例1:

// C# program to demonstrate the 
// Decimal.Subtract(Decimal, Decimal) 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // Declaring the decimal 
            // variables 
            Decimal a1 = .01m; 
            Decimal a2 = .03m; 
  
            // Subtracting the two Decimal value 
            // using Subtract() method 
            Decimal value = Decimal.Subtract(a1, a2); 
  
            // Display the Result 
            Console.WriteLine("Result is : {0}", 
                                         value); 
        } 
  
        catch (OverflowException e) { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
Result is : -0.02

示例2:對於OverflowException

// C# program to demonstrate the 
// Decimal.Subtract(Decimal, Decimal) 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // Declaring the decimal variables 
            Decimal a1 = Decimal.MinValue; 
            Decimal a2 = Decimal.MaxValue; 
  
            // Subtracting the two Decimal value 
            // using Subtract() method; 
            Decimal value = Decimal.Subtract(a1, a2); 
  
            // Display the Result 
            Console.WriteLine("Result is : {0}", 
                                        value); 
        } 
  
        catch (OverflowException e)  
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
Exception Thrown: System.OverflowException

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Decimal.Subtract() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。