C# Math

C# Math Class

While basic arithmetic operators (+, -, *, /) handle simple calculations, C# provides a built-in Math class located in the System namespace that offers methods for more complex mathematical tasks.


Maximum and Minimum

To find the highest or lowest value of two numbers, use Math.Max(x, y) and Math.Min(x, y).

Console.WriteLine(Math.Max(5, 10));  // Returns 10
Console.WriteLine(Math.Min(5, 10));  // Returns 5

Square Root

The Math.Sqrt(x) method returns the square root of x.

Console.WriteLine(Math.Sqrt(64));  // Returns 8

Absolute Value

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

Console.WriteLine(Math.Abs(-4.7));  // Returns 4.7

Rounding Numbers

The Math.Round(x) method rounds a floating-point value to the nearest integer. Note that a value like .5 typically rounds to the nearest even number in C# (this is known as Banker's Rounding).

Console.WriteLine(Math.Round(9.99)); // Returns 10

Power

The Math.Pow(x, y) method returns the value of x to the power of y.

Console.WriteLine(Math.Pow(2, 3)); // Returns 8 (2 * 2 * 2)

Ceiling and Floor

If you want to round a number specifically up or down to the nearest whole number, regardless of the decimal value, you can use Math.Ceiling() and Math.Floor().

Console.WriteLine(Math.Ceiling(9.1)); // Returns 10
Console.WriteLine(Math.Floor(9.9));   // Returns 9

Additional Math Methods

The Math class has many other useful methods and properties:

Console.WriteLine(Math.PI);             // Returns 3.141592653589793
Console.WriteLine(Math.Truncate(9.99)); // Returns 9

Exercise

?

Which method returns the square root of a number?