MathF.Abs() Method in C# with Examples

The MathF.Abs() method in C# is used to return the absolute value of a float number. The absolute value represents the non-negative value of a number without regard to its sign. For example, the absolute value of both -5.5f and 5.5f is 5.5f.

This method is part of the System namespace and is specifically designed for float operations, providing better performance than the generic Math.Abs() method when working with single-precision floating-point numbers.

Syntax

Following is the syntax for the MathF.Abs() method −

public static float Abs(float val);

Parameters

  • val − A single-precision floating-point number whose absolute value is to be returned.

Return Value

Returns a float value that represents the absolute value of the specified number. If the input is float.NaN, it returns float.NaN. If the input is positive or negative infinity, it returns positive infinity.

MathF.Abs() Behavior 0 -3.5f 3.5f Both return 3.5f

Using MathF.Abs() with Positive and Negative Values

Example

using System;

public class Demo {
   public static void Main() {
      float val1 = 20.5f;
      float val2 = -89.5f;
      Console.WriteLine("Absolute float value1 = " + (MathF.Abs(val1)));
      Console.WriteLine("Absolute float value2 = " + (MathF.Abs(val2)));
   }
}

The output of the above code is −

Absolute float value1 = 20.5
Absolute float value2 = 89.5

Using MathF.Abs() with Small Decimal Values

Example

using System;

public class Demo {
   public static void Main() {
      float val1 = 0.1f;
      float val2 = -1.0f;
      float val3 = 0.0f;
      Console.WriteLine("Absolute float value1 = " + (MathF.Abs(val1)));
      Console.WriteLine("Absolute float value2 = " + (MathF.Abs(val2)));
      Console.WriteLine("Absolute float value3 = " + (MathF.Abs(val3)));
   }
}

The output of the above code is −

Absolute float value1 = 0.1
Absolute float value2 = 1
Absolute float value3 = 0

Using MathF.Abs() with Special Float Values

Example

using System;

public class Demo {
   public static void Main() {
      float posInfinity = float.PositiveInfinity;
      float negInfinity = float.NegativeInfinity;
      float notANumber = float.NaN;
      
      Console.WriteLine("Abs of PositiveInfinity = " + MathF.Abs(posInfinity));
      Console.WriteLine("Abs of NegativeInfinity = " + MathF.Abs(negInfinity));
      Console.WriteLine("Abs of NaN = " + MathF.Abs(notANumber));
   }
}

The output of the above code is −

Abs of PositiveInfinity = Infinity
Abs of NegativeInfinity = Infinity
Abs of NaN = NaN

Conclusion

The MathF.Abs() method provides an efficient way to obtain the absolute value of float numbers in C#. It handles special cases like infinity and NaN appropriately, making it reliable for mathematical computations involving single-precision floating-point numbers.

Updated on: 2026-03-17T07:04:35+05:30

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements