Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a double to an int in Java by rounding it down?

Tags:

java

casting

I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99

like image 477
badpanda Avatar asked Jan 26 '10 23:01

badpanda


People also ask

Does casting a double to an int round down or up?

When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value.

Does Java round up or down when casting to int?

The answer is Yes. Java does a round down in case of division of two integer numbers.

Do doubles round down in Java?

The same (int)doubles round up and down in Java - Stack Overflow.

How do you round down an integer in Java?

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.


1 Answers

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)

like image 54
Xorlev Avatar answered Sep 28 '22 03:09

Xorlev