find and solve || findandsolve.com
Please wait.....

C# Math

The C# Math class has many methods which allows us to perform mathematical tasks on numbers.

Math class methods

Min(), Max()

Both functions take two numbers of any data type as parameters Min() returns the smallest number, Max() returns the greatest one.


Round(), Ceiling(), Floor() and Truncate()

All three functions are related to rounding. Round() takes a decimal number as parameter and returns the rounded number of the double data type (from 0.5 it rounds upwards, otherwise downwards). Ceiling() upwards and Floor() rounds downwards no matter what Truncate() cuts the decimal part off and leaves whole number part intact( does not round ).

Floor() and Truncate() behave differently for negative numbers. Floor() rounds negative numbers down to the next “more negative” number, Truncate() always rounds to zero when the input is negative.

Decimal numbers are rounded and stored them in int variables:

double d = 2.65;
int a = (int)Math.Round(d);

Casting to int is necessary despite of the Round() method returns a whole number. However, it is still of the double type, due to the fact that all mathematical functions work with double.


Pow() and Sqrt()

Pow() takes two double parameters. The first is the base of power and the second is exponent. To calculate 2^3, the code will be following:

Console.WriteLine(Math.Pow(2, 3));

Sqrt() is an abbreviation of Square Root, which returns the square root of the number given as a double. Both functions return a double as the result.


Math.Abs(x)

The Math.Abs(x) method returns the absolute (positive) value of x:

Example
Math.Abs (-4.5);
Math.Round()

Math.Round() rounds a number to the nearest whole number:

Example

Math.Round(8.99);