Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Decimal.Add() Method in C#
The Decimal.Add() method in C# is a static method that adds two specified decimal values and returns their sum. This method provides precise decimal arithmetic, which is essential for financial calculations where floating-point errors must be avoided.
Syntax
Following is the syntax −
public static decimal Add(decimal val1, decimal val2);
Parameters
val1 − The first decimal value to add.
val2 − The second decimal value to add.
Return Value
Returns a decimal value that represents the sum of val1 and val2.
Using Decimal.Add() with Regular Values
Example
using System;
public class Demo {
public static void Main() {
decimal val1 = 3.07m;
decimal val2 = 4.09m;
Console.WriteLine("Decimal 1 = " + val1);
Console.WriteLine("Decimal 2 = " + val2);
decimal res = Decimal.Add(val1, val2);
Console.WriteLine("Result (Sum) = " + res);
}
}
The output of the above code is −
Decimal 1 = 3.07 Decimal 2 = 4.09 Result (Sum) = 7.16
Using Decimal.Add() with Extreme Values
Example
using System;
public class Demo {
public static void Main() {
decimal val1 = Decimal.MinValue;
decimal val2 = 8.21m;
Console.WriteLine("Decimal 1 = " + val1);
Console.WriteLine("Decimal 2 = " + val2);
decimal res = Decimal.Add(val1, val2);
Console.WriteLine("Result (Sum) = " + res);
}
}
The output of the above code is −
Decimal 1 = -79228162514264337593543950335 Decimal 2 = 8.21 Result (Sum) = -79228162514264337593543950327
Decimal.Add() vs + Operator
The Decimal.Add() method is functionally equivalent to using the + operator. Both approaches provide the same precision and results −
Example
using System;
public class Demo {
public static void Main() {
decimal val1 = 15.75m;
decimal val2 = 24.25m;
decimal methodResult = Decimal.Add(val1, val2);
decimal operatorResult = val1 + val2;
Console.WriteLine("Using Decimal.Add(): " + methodResult);
Console.WriteLine("Using + operator: " + operatorResult);
Console.WriteLine("Results are equal: " + (methodResult == operatorResult));
}
}
The output of the above code is −
Using Decimal.Add(): 40.00 Using + operator: 40.00 Results are equal: True
Conclusion
The Decimal.Add() method provides a static way to add two decimal values with high precision. While functionally equivalent to the + operator, it offers a consistent API style for decimal arithmetic operations alongside other static methods like Decimal.Subtract() and Decimal.Multiply().
