How do I round a float upwards to the nearest int in C#?

In C#, how do I round a float upwards to the nearest int?

I see Math.Ceiling and Math.Round, but these returns a decimal. Do I use one of these then cast to an Int?


Solution 1:

If you want to round to the nearest int:

int rounded = (int)Math.Round(precise, 0);

You can also use:

int rounded = Convert.ToInt32(precise);

Which will use Math.Round(x, 0); to round and cast for you. It looks neater but is slightly less clear IMO.


If you want to round up:

int roundedUp = (int)Math.Ceiling(precise);

Solution 2:

Off the top of my head:

float fl = 0.678;
int rounded_f = (int)(fl+0.5f);

Solution 3:

(int)Math.Round(myNumber, 0)