Home Communities
IT Knowledge
Inspiration
Languages
EN

# C# / .NET - Math.Abs() method example

0 points
Created by:
338

The `Math.Abs()` function returns the absolute value of a number.

The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

Popular usage examples:

``````using System;

public class Program
{
public static void Main(string[] args)
{
Console.WriteLine( Math.Abs( 2 )); // 2
Console.WriteLine( Math.Abs(-2 )); // 2

Console.WriteLine( Math.Abs( 2.54)); // 2.54
Console.WriteLine( Math.Abs(-2.54)); // 2.54

Console.WriteLine( Math.Abs(  0   )); // 0
Console.WriteLine( Math.Abs( 3 + 5)); // 8
Console.WriteLine( Math.Abs( 3 - 5)); // 2
}
}``````

## 1. Documentation

 Syntax ``````namespace System { public static class Math { // ... public static decimal Abs(decimal value) { ... } public static double Abs(double value) { ... } public static short Abs(short value) { ... } public static int Abs(int value) { ... } public static long Abs(long value) { ... } public static sbyte Abs(sbyte value) { ... } public static float Abs(float value) { ... } // ... } }`````` Parameters `value` - `decimal`, `double`, `short`, `int`, `long`, `sbyte` or `float` value (primitive value). Result The absolute value calculated from the `number` (primitive value). Description `Math.Abs()` is a static method that takes only one parameter and returns absolute number parameter value. The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

## 2. Math.Abs() custom implementation

``````using System;

class Program
{
static double Abs(double x)
{
if (x < 0) {
return -x;
}
return x;
}

static void Main(string[] args)
{
Console.WriteLine( Abs(2.0) ); // 2
Console.WriteLine( Abs(-2.0)); // 2
Console.WriteLine( Abs(0.0) ); // 0
}
}``````

## References

1. Absolute value - wikipedia
Join to our subscribers to be up to date with content, news and offers.