Languages
[Edit]
EN

C# / .NET - Math.Abs() method example

0 points
Created by:
Barmar
338

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
namespace System
{
    public static class Math
    {
        // ...
        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) { ... }
        // ...
    }
}
Parametersvalue - decimaldouble, shortintlong, sbyte or float value (primitive value).
ResultThe absolute value calculated from the number (primitive value).
Description

Math.Abs() is a static method that takes only one parameter and returns absolute number parameter value. The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

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
    }
}

References

  1. Absolute value - wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - Math.abs()

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join