C# Math - Complete Guide
Introduction to C# Math Operations
The Math class in C# provides a comprehensive set of mathematical functions and constants for performing common and advanced numeric operations. It is a static class in the System namespace whose methods primarily operate on double values (use MathF for single-precision float scenarios).
Knowing how to apply Math APIs—trigonometric, logarithmic, exponential, rounding, comparison, and utility helpers—is useful across domains like scientific computing, finance, simulations, game development, and analytics.
Math Constants and Basic Functions
Math exposes important constants (Math.PI and Math.E) and basic functions such as Abs, Sqrt, Pow, and Exp, along with Min/Max and Sign for comparisons. Rounding helpers include Round, Floor, Ceiling, and Truncate.
Note that Math.Round by default uses midpoint rounding to even (banker’s rounding). Overloads let you specify the number of digits and MidpointRounding behavior.
using System;
namespace MathBasicExample
{
class Program
{
static void Main(string[] args)
{
// Mathematical constants
Console.WriteLine($"Math.PI: {Math.PI}");
Console.WriteLine($"Math.E: {Math.E}");
// Basic functions
Console.WriteLine($"\nAbsolute value of -10: {Math.Abs(-10)}");
Console.WriteLine($"Square root of 25: {Math.Sqrt(25)}");
Console.WriteLine($"2 raised to power 8: {Math.Pow(2, 8)}");
Console.WriteLine($"e raised to power 2: {Math.Exp(2)}");
// Rounding functions
double number = 3.756;
Console.WriteLine($"\nOriginal number: {number}");
Console.WriteLine($"Math.Round: {Math.Round(number)}");
Console.WriteLine($"Math.Round with 1 decimal: {Math.Round(number, 1)}");
Console.WriteLine($"Math.Floor: {Math.Floor(number)}");
Console.WriteLine($"Math.Ceiling: {Math.Ceiling(number)}");
Console.WriteLine($"Math.Truncate: {Math.Truncate(number)}");
// Sign and Min/Max
Console.WriteLine($"\nMath.Sign(10): {Math.Sign(10)}");
Console.WriteLine($"Math.Sign(-5): {Math.Sign(-5)}");
Console.WriteLine($"Math.Sign(0): {Math.Sign(0)}");
Console.WriteLine($"\nMath.Min(10, 20): {Math.Min(10, 20)}");
Console.WriteLine($"Math.Max(10, 20): {Math.Max(10, 20)}");
}
}
}
Math.PI: 3.141592653589793 Math.E: 2.718281828459045 Absolute value of -10: 10 Square root of 25: 5 2 raised to power 8: 256 e raised to power 2: 7.38905609893065 Original number: 3.756 Math.Round: 4 Math.Round with 1 decimal: 3.8 Math.Floor: 3 Math.Ceiling: 4 Math.Truncate: 3 Math.Sign(10): 1 Math.Sign(-5): -1 Math.Sign(0): 0 Math.Min(10, 20): 10 Math.Max(10, 20): 20