How to combine float to nearest int in C #?

In C #, how do I combine a float with the closest int?

I see Math.Ceiling and Math.Round, but they return a decimal number. Do I use one of them and then apply to Int?

+42
c # rounding
May 25 '09 at 12:04 a.m.
source share
6 answers

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); for rounding and throwing for you. It looks neater, but a little less clear. IMO.




If you want to round up :

 int roundedUp = (int)Math.Ceiling(precise); 
+101
May 25 '09 at 12:13 a.m.
source share

Above my head:

 float fl = 0.678; int rounded_f = (int)(fl+0.5f); 
+9
May 25 '09 at 12:10 a.m.
source share

(int) Math.Round (myNumber, 0)

+3
May 25 '09 at
source share

The easiest way is to simply add 0.5f to it and then apply it to int.

+2
May 25 '09 at
source share

Do I use one of them and then apply to Int?

Yes. It's not a problem. Decimals and doubles can accurately represent integers, so there will be no representation error. (You will not get a case, for example, where Round returns 4.999 ... instead of 5.)

+1
May 25 '09 at
source share

You can apply to int if you are sure that it is in the range for int (Int32.MinValue - Int32.MaxValue).

0
May 25 '09 at 7:01
source share



All Articles