Decimal.Subtract() Method in C#


The Decimal.Subtract() method in C# is used to subtract two specified Decimal values.

Syntax

Following is the syntax −

public static decimal Subtract (decimal val1, decimal val2);

Above, va1 is the minuend, whereas val2 is the subtrahend.

Example

Let us now see an example to implement the Decimal.Subtract() method −

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);
   }
}

Output

This will produce the following output −

Decimal 1 = 3.45
Decimal 2 = 2.35
Result (Subtract) = 1.10

Example

Let us now see another example to implement the Decimal.Subtract() method. It shows an error since the value is too large or too small for decimal −

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);
   }
}

Output

This will produce the following output −

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

Updated on: 13-Nov-2019

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements