C# Math
The C# Math class gives you a ready-made toolbox of methods for common mathematical work, so you don't have to write formulas for things like square roots, rounding, or powers yourself.
The System.Math Class
C# has a built-in class named Math that lives in the System namespace. It contains a large set of static methods that perform mathematical tasks on numbers. Because the methods are static, you call them directly on the class name using Math.MethodName(...) without creating an object first.
Two of the most frequently used methods are Math.Max() and Math.Min(). They compare two values and return the larger or the smaller one, which is handy when you want the highest score, the cheapest price, or a safe upper limit.
Max and Min
int highest = Math.Max(5, 10);
int lowest = Math.Min(5, 10);
Console.WriteLine(highest); // Outputs 10
Console.WriteLine(lowest); // Outputs 5Square Root, Absolute Value, and Powers
Math.Sqrt() returns the square root of a number, Math.Abs() returns the absolute (non-negative) value, and Math.Pow() raises a number to the power of another. These methods return a double, so store the result in a double variable to keep the decimals.
Common calculations
double root = Math.Sqrt(64); // 8
double distance = Math.Abs(-4.7); // 4.7
double power = Math.Pow(2, 3); // 2 * 2 * 2 = 8
Console.WriteLine(root);
Console.WriteLine(distance);
Console.WriteLine(power);Rounding Numbers
When you work with decimals you often need a whole number. C# gives you three rounding helpers: Math.Round() goes to the nearest whole number, Math.Ceiling() always rounds up, and Math.Floor() always rounds down.
Rounding a price
double price = 9.65;
Console.WriteLine(Math.Round(price)); // 10
Console.WriteLine(Math.Ceiling(price)); // 10
Console.WriteLine(Math.Floor(price)); // 9Handy Math methods
Exercise: C# Math
What does Math.Round(2.5) return by default in C#?