This post will discuss how to convert a floating-point number to the nearest int in C#.

1. Using Math.Round() method

The most common approach to round a value to the nearest integer is using the Math.Round() method. However, this method returns a Decimal instead of an integer, and you need to cast the result to an integer. The following example illustrates.

Download  Run Code

 
The Math.Round() method uses the round to nearest even convention by default. It is overloaded to take the MidpointRounding Enum, which specifies the strategy used for rounding the specified number. For example, the following code uses the rounding convention of MidpointRounding.AwayFromZero.

Download  Run Code

 
For more information on rounding numbers with midpoint values, see the official documentation of the Midpoint values and rounding conventions.

2. Using Math.Ceiling() method

An alternative to the Math.Round() method is to use Math.Ceiling() method. It returns the nearest integral value greater than or equal to the specified number. The following example shows the invocation for this method:

Download  Run Code

3. Using Convert.ToInt32() method

Both Math.Round() and Math.Ceiling() methods returns a Decimal instead of an integral value. You can also use the Convert.ToInt32(Decimal) method, which converts the specified decimal number value to the nearest 32-bit signed integer.

Download  Run Code

4. Using Math.Floor() method

Finally, if you need to round down a floating-point number to a nearest int, use Math.Floor() method. It returns the largest integer value less than or equal to the specified number.

Download  Run Code

 
Note that this is equivalent to explicit conversion using the casting, as shown below:

Download  Run Code

That’s all about converting a floating-point number to the nearest int in C#.