Math.Abs
An absolute value is not negative. It is the same as the original value but with no negative sign. With absolute values, we can avoid accessing negative indexes in arrays.
The Math.Abs
method in .NET provides a tested absolute value function. It deals with certain edge cases (like already-positive numbers).
Consider the values -1000 and 20. When we convert them into their absolute values, we get 1000 and 20—the minus sign is eliminated.
-1000 Abs() 1000 20 Abs() 20
It is usually trivial to convert variables to positive values from negative values. The Math.Abs
method provides some error-checking that may be useful.
double
and a positive double
.using System; // Compute 2 absolute values. int value1 = -1000; int value2 = 20; int abs1 = Math.Abs(value1); int abs2 = Math.Abs(value2); // Write integral results. Console.WriteLine(value1); Console.WriteLine(abs1); Console.WriteLine(value2); Console.WriteLine(abs2); // End. Console.WriteLine(); // Compute 2 double absolute values. double value3 = -100.123; double value4 = 20.20; double abs3 = Math.Abs(value3); double abs4 = Math.Abs(value4); // Write double results. Console.WriteLine(value3); Console.WriteLine(abs3); Console.WriteLine(value4); Console.WriteLine(abs4);-1000 1000 20 20 -100.123 100.123 20.2 20.2
Math.Abs()
on value types (int
, short
, long) will use a conditional check that tests if the number if already positive. If the number is positive, it is returned unchanged.
For number types such as decimal, double
and float
, other implementations are called. Math.Abs
is a wrapper method in these cases.
double
and float
, it is important to use Math.Abs
instead of checking for positive yourself.From the hardware perspective, it is easier to flip the sign bit on a signed integer type. You can apply the unary minus (negation) operator.
We tested Math.Abs
, an absolute value function. This method accepts decimal, double
, Int16
, Int32
, Int64
and float
types (and all keywords that are aliased to those).