Loading...

C# Math Library

Learn how to use the C# Math library, including Pow, Sqrt, Round, Abs, and other essential mathematical methods with examples.

In C#, the System.Math class contains many built-in methods and constants for mathematical calculations. Since this class is defined as static, methods are called directly as Math.Method() without the need to create an object. Let’s take a look at the most commonly used methods.


Absolute Value (Abs)


int a = -15;
Console.WriteLine(Math.Abs(a)); // 15

Minimum and Maximum (Min, Max)


int x = 8, y = 20;
Console.WriteLine(Math.Min(x, y)); // 8
Console.WriteLine(Math.Max(x, y)); // 20

Square Root (Sqrt)


double number = 81;
Console.WriteLine(Math.Sqrt(number)); // 9

Power (Pow)


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

Rounding (Round, Ceiling, Floor)


double d = 4.7;

Console.WriteLine(Math.Round(d));   // 5 (rounds to the nearest)
Console.WriteLine(Math.Ceiling(d)); // 5 (always rounds up)
Console.WriteLine(Math.Floor(d));   // 4 (always rounds down)

Division Remainder (DivRem)


int quotient, remainder;
remainder = Math.DivRem(17, 5, out quotient);

Console.WriteLine("Quotient: " + quotient); // 3
Console.WriteLine("Remainder: " + remainder); // 2

Trigonometric Functions (Sin, Cos, Tan)


double angle = Math.PI / 4; // 45 degrees (in radians)

Console.WriteLine(Math.Sin(angle)); // 0.707...
Console.WriteLine(Math.Cos(angle)); // 0.707...
Console.WriteLine(Math.Tan(angle)); // 1

Angle Conversion (Radians/Degrees, PI Constant)


double degree = 180;
double radian = degree * (Math.PI / 180);

Console.WriteLine(radian); // 3.14159...

Logarithm (Log, Log10)


Console.WriteLine(Math.Log(100));   // natural log (base e)
Console.WriteLine(Math.Log10(100)); // base-10 log

Maximum and Minimum Double Values


Console.WriteLine(double.MaxValue);
Console.WriteLine(double.MinValue);

Square Root and Power Combination


double number = 256;
double result = Math.Sqrt(Math.Pow(number, 2)); 
Console.WriteLine(result); // 256 (first squared, then square root)

Using with Absolute Value


int diff = -50;
Console.WriteLine(Math.Abs(diff)); // 50

TL;DR

  • Math.Abs: Returns the absolute value.
  • Math.Min, Math.Max: Choose between two numbers.
  • Math.Sqrt, Math.Pow: Square root and exponentiation.
  • Math.Round, Ceiling, Floor: Rounding operations.
  • Math.Sin, Cos, Tan: Trigonometric functions.
  • Math.Log, Log10: Natural and base-10 logarithms.
  • Math.PI: Constant for the value of Pi.