Use the lround Function to Round Floating-Point Number to the Nearest Integer and Return Integral Type. The lround function, on the other hand, round to the nearest in integer and return the integral value.
Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.
Rounding to the Nearest Integer If the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.
In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
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);
Off the top of my head:
float fl = 0.678;
int rounded_f = (int)(fl+0.5f);
(int)Math.Round(myNumber, 0)
The easiest is to just add 0.5f
to it and then cast this to an int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With