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:
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(string[] args)
6
{
7
Console.WriteLine( Math.Abs( 2 )); // 2
8
Console.WriteLine( Math.Abs(-2 )); // 2
9
10
Console.WriteLine( Math.Abs( 2.54)); // 2.54
11
Console.WriteLine( Math.Abs(-2.54)); // 2.54
12
13
Console.WriteLine( Math.Abs( 0 )); // 0
14
Console.WriteLine( Math.Abs( 3 + 5)); // 8
15
Console.WriteLine( Math.Abs( 3 - 5)); // 2
16
}
17
}
Syntax |
xxxxxxxxxx 1 namespace System 2 { 3 public static class Math 4 { 5 // ... 6 public static decimal Abs(decimal value) { ... } 7 public static double Abs(double value) { ... } 8 public static short Abs(short value) { ... } 9 public static int Abs(int value) { ... } 10 public static long Abs(long value) { ... } 11 public static sbyte Abs(sbyte value) { ... } 12 public static float Abs(float value) { ... } 13 // ... 14 } 15 } |
Parameters | value - decimal , double , short , int , long , sbyte or float value (primitive value). |
Result | The absolute value calculated from the number (primitive value). |
Description |
|
xxxxxxxxxx
1
using System;
2
3
class Program
4
{
5
static double Abs(double x)
6
{
7
if (x < 0) {
8
return -x;
9
}
10
return x;
11
}
12
13
static void Main(string[] args)
14
{
15
Console.WriteLine( Abs(2.0) ); // 2
16
Console.WriteLine( Abs(-2.0)); // 2
17
Console.WriteLine( Abs(0.0) ); // 0
18
}
19
}