tags:

views:

383

answers:

5

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

Any ideas? :D

+3  A: 
Math.floor(n)

where n is a double. This'll actually return a double, it seems, so make sure that you typecast it after.

Austin Fitzpatrick
No need to floor before cast, see Xorlev's answer.
mizipzor
@miz: The semantics are different for negative numbers, though.
Joey
A: 

Try using Math.floor.

John at CashCommons
Floor() is not needed.
TBH
+3  A: 

This works fine int i = (int) dbl;

fastcodejava
+3  A: 

(int)99.99999

Will be 99. Casting a double to an int does not round, it'll discard the fraction part.

leeeroy
+10  A: 

Casting to an int implicitly drops any decimal part. No need to call Math.floor().

Simply typecast with (int), e.g.:

System.out.println((int)(99.9999)); // Returns 99
Xorlev
Note that `Math.floor` *does* produce a different result for negative numbers than a simple typecast.
Joey