Welcome to my little corner of the internet
C# Math.Abs Method

c# Absolute Value And The math.abs Method

c# Absolute Value – I am adding this short post for my son as an easy lookup while I teach him to program. An absolute value is the distance to 0 and the words “absolute value” are more complicated than the concept. -5 is 5 from 0 so, the absolute value of -5 is 5. I am sure that when you were in middle school you simply removed the – from the number but I am fairly sure that at the time you did not realize it was simply the distance to 0. 

So -4 and 4 are simply 4 units to 0;

c# absolute value

c# Absolute Value and her Many Overloads

Now in C#, we use the method Abs that resides off of the Math Class.

C# Math.Abs Method

It has 7 few overloads including Decimal, Double, Int16, Int32, Int64, SByte, and Single. 

Abs(Decimal)Returns the absolute value of a Decimal number.
Abs(Double)Returns the absolute value of a double-precision floating-point number.
Abs(Int16)Returns the absolute value of a 16-bit signed integer.
Abs(Int32)Returns the absolute value of a 32-bit signed integer.
Abs(Int64)Returns the absolute value of a 64-bit signed integer.
Abs(SByte)Returns the absolute value of an 8-bit signed integer.
Abs(Single)Returns the absolute value of a single-precision floating-point number.

Here is an example of its use. I have used an array of a few types to demonstrate the outputs in a Console App.

				
					using System;

class Program

{

    static void Main(string[] args)

    {

        //c# absolute value - The Repeat code was left for readability and simplicity. I probably could have put this in a method with a Genertic T as the Type

        int[] integers = { -343254, 343, -2, 345345345 };

        decimal[] decimals = { -2343.23M, 23423.334M, -1.2M };

        short[] shorts = { -32767, 32767, 1, 34, -33 };

        foreach (var value in integers)

        {           

            Console.WriteLine("The Abslute value of " + value.ToString() + " is " + Math.Abs(value));

        }

        foreach (var value in decimals)

        {

            Console.WriteLine("The Abslute value of " + value.ToString() + " is " + Math.Abs(value));

        }

        foreach (var value in shorts)

        {

            Console.WriteLine("The Abslute value of " + value.ToString() + " is " + Math.Abs(value));

        }

        Console.ReadLine();

    }    

}
				
			

Share This Post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email

More to Explorer

Scott Carpenter in SEALAB II

Scott Carpenter

My father named me after this man(Scott Carpenter). He had the opportunity to work with him during the development of Project Redstone/Mercury. I missed the

Read More »