Difference between 2 numbers
result = Math.Abs(value1 - value2);
Just adding this, as nobody wrote it here:
While you can surely use
Math.Abs(number1 - number2);
which is the easiest solution (and accepted answer), I wonder nobody wrote out what Abs actually does. Here's a solution that works in Java, C, C# and every other language with C like syntax:
int result = number1 - number2;
if (result < 0) {
result *= -1;
}
It's that simple. You can also write it like this:
int result = number1 > number2 ? number1 - number2 : number2 - number1;
The last one could be even faster once it got compiled; both have one if and one subtraction, but the first one has a multiplication in some cases, the last one has not. Why only in some cases? Some CPUs have a "swap sign" operation and the compiler recognizes what *= -1
does, it just swaps the sign, so instead of a multiplication, it will issue a swap sign operation for CPUs that offer it and this operation is as fast as a CPU operation can get (usually one clock cycle).
The first code example is actually doing what Abs is doing in most implementations to make use of "swap sign" where supported, the last one will be faster on CPUs that have no "swap sign" and were multiplications are more expensive than additions (on modern CPUs they are often equally fast).
You can do it like this
public decimal FindDifference(decimal nr1, decimal nr2)
{
return Math.Abs(nr1 - nr2);
}