round() Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.
Since double is bigger data type than int, you can simply downcast double to int in Java. double is 64-bit primitive value and when you cast it to a 32-bit integer, anything after the decimal point is lost.
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);
I know this question is old, but I came across it in my search for the answer to my similar question. I thought I would share the very useful tip that I have been given.
When converting to int, simply add .5
to your value before downcasting. As downcasting to int
always drops to the lower number (e.g. (int)1.7 == 1
), if your number is .5
or higher, adding .5
will bring it up into the next number and your downcast to int
should return the correct value. (e.g. (int)(1.8 + .5) == 2
)
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