C# Math Class

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Math class in C#

In C#, the Math class is a part of the .NET Framework’s standard library and provides a wide range of mathematical functions and constants for performing common mathematical operations. It is a static class, which means you don’t need to create an instance of it; you can access its methods and properties directly.

Key Features of the Math Class:

Static Methods: The Math class consists of various static methods that allow you to perform mathematical operations, such as trigonometric functions, logarithms, exponentiation, and more.

Mathematical Constants: It provides a collection of mathematical constants, including Math.PI for the value of π (pi) and Math.E for the base of the natural logarithm.

Common Methods of the Math Class:

Trigonometric Functions: You can use methods like Math.Sin(), Math.Cos(), and Math.Tan() to compute the sine, cosine, and tangent of angles, respectively.

Exponential and Logarithmic Functions: The Math class offers functions like Math.Exp() for exponentiation and math. Log() for logarithms, including options for specifying the base of the logarithm.

Rounding and Absolute Value: Methods like Math.Round(), Math.Floor(), and Math.Ceiling() help with rounding numbers to integers or specific decimal places. Math.Abs() returns the absolute value of a number.

Square Root: You can use Math.Sqrt() to calculate the square root of a number.

Random Number Generation: The Math class provides methods for generating random numbers, such as Math.Random().

Min and Max Values:Math.Min() and Math.Max() help you find the minimum and maximum of two values, respectively.

Some of the common methods from the Math class in C#:

Math.Max() – Returns the larger of two numbers:

Example:

double maxNumber = Math.Max(10.5, 20.7);

Math.Min() – Returns the smaller of two numbers:

Example:

double minNumber = Math.Min(30.9, 15.3);

Math.Sqrt() – Calculates the square root of a number:

Example:

double squareRoot = Math.Sqrt(64.0);

Math.Abs() – Returns the absolute (non-negative) value of a number:

Example:

double absoluteValue = Math.Abs(-5.2);

Math.Round() – Rounds a number to the nearest integer:

Example:

double roundedNumber = Math.Round(7.6);

Math.Pow() – Raises a number to a specified power:

Example:

double result = Math.Pow(2.0, 3.0); // Calculates 2^3 (2 to the power of 3)

Math.Truncate() – Removes the decimal part of a number (rounds towards zero):

Example:

double truncatedValue = Math.Truncate(8.9);

These one-line examples demonstrate how to use each of the specified methods from the Math class to perform different mathematical operations.

Course Video