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.
That is, the answer is always rounding down.
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.
add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.
float x = 55; // stored as 54.999999...
x = x + 0.5 - (x<0); // x is now 55.499999...
int y = (int)x; // truncated to 55
C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.
A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer.
Casting is not a mathematical operation and doesn't behave as such. Try
int y = (int)round(x);
Casting to an int
truncates the value. Adding 0.5
causes it to do proper rounding.
int y = (int)(x + 0.5);
It is worth noting that what you're doing isn't rounding, it's casting. Casting using (int) x
truncates the decimal value of x
. As in your example, if x = 3.9995
, the .9995
gets truncated and x = 3
.
As proposed by many others, one solution is to add 0.5
to x
, and then cast.
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