How might I convert a double to the nearest integer value?
How do you convert a double into the nearest int?
double d = 1.234;
int i = Convert.ToInt32(d);
Reference
Handles rounding like so:
rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
Use Math.round()
, possibly in conjunction with MidpointRounding.AwayFromZero
eg:
Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3
You can also use function:
//Works with negative numbers now
static int MyRound(double d) {
if (d < 0) {
return (int)(d - 0.5);
}
return (int)(d + 0.5);
}
Depending on the architecture it is several times faster.
double d;
int rounded = (int)Math.Round(d);