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.
Method info. The Math.Abs method in .NET provides a tested absolute value function. It deals with certain edge cases (like already-positive numbers).
Required input, output. 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
Example. 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.
Tip The C# compiler does overload resolution based on the parameter type. It infers the appropriate method to use.
Internals. 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.
Detail An overflow condition is checked and the unary negation operator is applied, which results in a positive number.
Tip If the overflow condition is not useful, you can enhance performance by checking for positive numbers yourself.
Notes, other types. For number types such as decimal, double and float, other implementations are called. Math.Abs is a wrapper method in these cases.
Tip For double and float, it is important to use Math.Abs instead of checking for positive yourself.
Discussion. 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.
Tip You can take the absolute value of a number that is always negative by simply using the unary negation operator.
Summary. 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).
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 11, 2023 (edit).