EN
C# / .NET - Math.Abs() method example
0
points
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 |
|
Parameters | value - decimal , double , short , int , long , sbyte or float value (primitive value). |
Result | The absolute value calculated from the number (primitive value). |
Description |
|
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
}
}