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.
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
The Math.Sqrt(x) method returns the square root of x.
Console.WriteLine(Math.Sqrt(64)); // Returns 8
The Math.Abs(x) method returns the absolute (positive) value of a number.
Console.WriteLine(Math.Abs(-4.7)); // Returns 4.7
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
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)
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().
Math.Ceiling(x) rounds x UP to the nearest integer.Math.Floor(x) rounds x DOWN to the nearest integer.Console.WriteLine(Math.Ceiling(9.1)); // Returns 10 Console.WriteLine(Math.Floor(9.9)); // Returns 9
The Math class has many other useful methods and properties:
Math.PI: A property that returns the value of Pi (3.14159...).Math.Sign(x): Returns an integer that indicates the sign of a number (1 for positive, -1 for negative, 0 for zero).Math.Truncate(x): Calculates the integral part of a number (removes the decimal part entirely without rounding).Console.WriteLine(Math.PI); // Returns 3.141592653589793 Console.WriteLine(Math.Truncate(9.99)); // Returns 9
Which method returns the square root of a number?