C# Math

As well as the operators C# provides, there are also a number of methods to carry out certain mathematical operations and compare values.


The ‘Ceiling’ method takes a single value and rounds it up to the nearest whole number.

float x = 3.4f;


Here, the value of ‘x’, 3.4, is rounded up to four and displayed in the console.


The ‘Floor’ method is the opposite of ‘Ceiling’. It again takes a single value, but rounds it down to the nearest whole number, instead of up.

float x = 3.9f;


The resulting output to the console in this instance is three.


As the name suggests, ‘Min’ finds a minimum value, out of two values that are passed to it. These two values can be integers, floating-point numbers or a mixture of the two.

int x = 2;
float y = 3.9f;

Console.WriteLine(Math.Min(x, y));

This determines that the value of ‘x’ is the minimum, or smallest, out of the two.


‘Max’ works in a similar manner to ‘Min’, taking two values, but this time it works out which one is the larger of the two.

int x = 2;
float y = 3.9f;

Console.WriteLine(Math.Max(x, y));

This time the value of ‘y’ is displayed, with it being the larger of the two.


Like both the ‘Min’ and ‘Max’ methods, ‘Pow’ takes two values. It raises the first value to the power of the second, in this case, two to the power three and produces a result of eight.

int x = 2;
int y = 3;

Console.WriteLine(Math.Pow(x, y));


The ‘Round’ method can be used to round a given value to the specified number of decimal places.

float x = 2.4567f;

Console.WriteLine(Math.Round(x, 2));

The value of ‘x’, 2.4567, is rounded to the specified two decimal places to give a result of 2.46.


In order to find the square root of a number, the ‘Sqrt’ method can be utilised, as show in the example below, where it is used to find the square root of four, which is two.

int x = 4;



The final method discussed here is ‘Truncate’, which can be used to remove everything after the decimal point. There is no rounding involved, it just leaves the value before the decimal point.

float x = 4.58769f;


The .58769 is removed from the value of ‘x’ to leave four.

This is just a selection of the methods available. Further details can be found below.

Further Reading