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 5

Square 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));   // 9

Handy Math methods

MethodDescriptionExample result
Math.Max(x, y)Returns the larger of two valuesMath.Max(3, 8) is 8
Math.Min(x, y)Returns the smaller of two valuesMath.Min(3, 8) is 3
Math.Sqrt(x)Returns the square rootMath.Sqrt(9) is 3
Math.Abs(x)Returns the absolute valueMath.Abs(-3) is 3
Math.Round(x)Rounds to the nearest whole numberMath.Round(3.6) is 4
Note: Math.Round() uses banker's rounding by default, meaning a value exactly halfway (like 2.5) rounds to the nearest even number (2). This can surprise beginners, so double-check results when a value ends in .5.

Exercise: C# Math

What does Math.Round(2.5) return by default in C#?