How to subtract one decimal value from another in C#
Overview
We use the decimal.Subtract() method to subtract one decimal value from another.
Syntax
public static decimal Subtract (decimal d1, decimal d2);
Parameters
d1: This is the minuend.d2: This is the subtrahend. We subtract this fromd1.
Return value
This method returns the subtraction result of two decimal values.
Example
// use Systemusing System;// create classclass DecimalSubtracter{// main methodstatic void Main(){// initialise decimal valuesdecimal d1 = 234.3m;decimal d2 = 3.5678m;decimal d3 = 34.45m;decimal d4 = 67.245m;// subtract decimal valuesdecimal r1 = Decimal.Subtract(d1,d2);decimal r2 = Decimal.Subtract(d3,d4);// print resultsConsole.WriteLine(r1);Console.WriteLine(r2);}}
Explanation
-
Line 11–14: We create some
decimalvalues,d1,d2,d3, andd4. -
Line 17: We subtract
d2fromd1usingdecimal.Subtract()and store the result inr1. -
Line 18: We subtract
d4fromd3using thedecimal.Subtract()method and store the result inr2. -
Line 21: We print the result of subtracting
d2fromd1. -
Line 22: We print the result of subtracting
d4fromd3.