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.Remainder() Method in C#
The Decimal.Remainder() method in C# is used to calculate the remainder after dividing two Decimal values. This method performs the same operation as the modulus operator (%) but is specifically designed for decimal precision calculations.
Syntax
Following is the syntax −
public static decimal Remainder(decimal val1, decimal val2);
Parameters
- val1 − The dividend (the number to be divided).
- val2 − The divisor (the number by which to divide).
Return Value
Returns a decimal value representing the remainder after dividing val1 by val2.
Using Decimal.Remainder() with Different Values
Example 1
using System;
public class Demo {
public static void Main() {
decimal val1 = 45.15m;
decimal val2 = 15.15m;
Console.WriteLine("Decimal 1 = " + val1);
Console.WriteLine("Decimal 2 = " + val2);
Console.WriteLine("After Division = " + (Decimal.Divide(val1, val2)));
Console.WriteLine("Remainder = " + (Decimal.Remainder(val1, val2)));
}
}
The output of the above code is −
Decimal 1 = 45.15 Decimal 2 = 15.15 After Division = 2.9801980198019801980198019802 Remainder = 14.85
Example 2
using System;
public class Demo {
public static void Main() {
decimal val1 = 1.00m;
decimal val2 = 1.00m;
Console.WriteLine("Decimal 1 = " + val1);
Console.WriteLine("Decimal 2 = " + val2);
Console.WriteLine("After Division = " + (Decimal.Divide(val1, val2)));
Console.WriteLine("Remainder = " + (Decimal.Remainder(val1, val2)));
}
}
The output of the above code is −
Decimal 1 = 1.00 Decimal 2 = 1.00 After Division = 1 Remainder = 0.00
Using Decimal.Remainder() vs Modulus Operator
Example
using System;
public class Demo {
public static void Main() {
decimal val1 = 17.5m;
decimal val2 = 5.2m;
Console.WriteLine("Dividend: " + val1);
Console.WriteLine("Divisor: " + val2);
Console.WriteLine("Using Decimal.Remainder(): " + Decimal.Remainder(val1, val2));
Console.WriteLine("Using % operator: " + (val1 % val2));
Console.WriteLine("Both results are equal: " + (Decimal.Remainder(val1, val2) == (val1 % val2)));
}
}
The output of the above code is −
Dividend: 17.5 Divisor: 5.2 Using Decimal.Remainder(): 1.9 Using % operator: 1.9 Both results are equal: True
Comparison
| Decimal.Remainder() | % Operator |
|---|---|
| Static method call | Infix operator |
| More explicit and readable | More concise syntax |
| Same mathematical result | Same mathematical result |
Conclusion
The Decimal.Remainder() method provides a precise way to calculate the remainder of decimal division operations. While it produces the same results as the modulus operator (%), it offers a more explicit method-based approach for remainder calculations with decimal precision.
