C# | Math.Abs() Method | Set – 1
In C#,
Abs() is a Math class method which is used to return the absolute value of a specified number. This method can be overload by passing the different type of parameters to it. There are total 7 methods in its overload list.
- Math.Abs(Decimal)
- Math.Abs(Double)
- Math.Abs(Int16)
- Math.Abs(Int32)
- Math.Abs(Int64)
- Math.Abs(SByte)
- Math.Abs(Single)
Math.Abs(Int64)
This method is used to return the absolute value of a 64-bit signed integer.
Syntax:
public static long Abs (long val);
Parameter:
val: It is the required number which is greater than Int64.MinValue, but less than or equal to Int64.MaxValue of type System.Int64.
Return Type: It returns a 64-bit signed integer say r, such that 0 ≤ r ≤ Int64.MaxValue.
Exception: This method will give OverflowException if the value of val is equals to Int64.MinValue.
Example:
Output:
Absolute value of 9223372036854775807 = 9223372036854775807
Absolute value of 78345482 = 78345482
Absolute value of -4687985 = 4687985
Absolute value of 0 = 0
Math.Abs(SByte)
This method is used to return the absolute value of an 8-bit signed integer.
Syntax:
public static sbyte Abs (sbyte val);
Parameter:
val: It is the required number which is greater than SByte.MinValue, but less than or equal to SByte.MaxValue of type System.SByte.
Return Type: It returns a 8-bit signed integer say r, such that 0 ≤ r ≤ SByte.MaxValue.
Exception: This method will give OverflowException if the value of val is equals to SByte.MinValue.
Example:
Output:
Absolute value of 127 = 127
Absolute value of 45 = 45
Absolute value of -41 = 41
Absolute value of 0 = 0
Math.Abs(Single)
This method is used to return the absolute value of a single-precision floating-point number.
Syntax:
public static float Abs (float val);
Parameter:
val: It is the required number which is greater than or equal to Single.MinValue, but less than or equal to MaxValue of type System.Single.
Return Type: It returns a single-precision floating-point number say r, such that 0 ≤ r ≤ Single.MaxValue.
Note:
- If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity.
- If the val is equal to NaN then return value will be NaN.
Example: