C# Tutorial C# Advanced C# References

C# Math - Abs() Method



The C# Abs() method returns the Absolute value (positive value) of the specified number. The method can be overloaded and it can take int, double, float and long arguments. The method can be overloaded and it can take decimal, double, short, int, long, sbyte, and float arguments. In special cases it returns the following:

  • If the argument is positive infinity or negative infinity, the method returns positive infinity.
  • If the argument is NaN, the method returns NaN.

Syntax

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 Specify a number whose Absolute value need to be determined.

Return Value

Returns the Absolute value (positive value) of the argument.

Example:

In the example below, Abs() method returns the Absolute value (positive value) of the specified number.

using System;

class MyProgram {
  static void Main(string[] args) {
    Console.WriteLine("Math.Abs(10) = "
                      + Math.Abs(10));
    Console.WriteLine("Math.Abs(-10) = "
                      + Math.Abs(-10));
    Console.WriteLine("Math.Abs(-5.5) = "
                      + Math.Abs(-5.5));
    Console.WriteLine("Math.Abs(-5.5f) = "
                      + Math.Abs(-5.5f));
    Console.WriteLine("Math.Abs(Double.NaN) = "
                      + Math.Abs(Double.NaN));
    Console.WriteLine("Math.Abs(Double.NegativeInfinity) = "
                      + Math.Abs(Double.NegativeInfinity));
    Console.WriteLine("Math.Abs(Double.PositiveInfinity) = "
                      + Math.Abs(Double.PositiveInfinity));                     
  }
}

The output of the above code will be:

Math.Abs(10) = 10
Math.Abs(-10) = 10
Math.Abs(-5.5) = 5.5
Math.Abs(-5.5f) = 5.5
Math.Abs(Double.NaN) = NaN
Math.Abs(Double.NegativeInfinity) = Infinity
Math.Abs(Double.PositiveInfinity) = Infinity

❮ C# Math Methods

5