I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value.
The answer is Yes. Java does a round down in case of division of two integer numbers.
The same (int)doubles round up and down in Java - Stack Overflow.
Java Math floor() The floor() method rounds the specified double value downward and returns it. The rounded value will be equal to a mathematical integer. That is, the value 3.8 will be rounded to 3.0 which is equal to integer 3.
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
This being said, it does have a different behavior from Math.floor
which rounds towards negative infinity (@Chris Wong)
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