Search code examples
javajava-8standardsstandards-compliance

Java Standard On Result Of Casting A Double To An Int


Say I have the following...

double d = 1.6;
int q = ( ( int ) d );

Will this always drop the just decimal point according to the Java standard, or could it round up or down according to the standard (Which more or less exists)?


Solution

  • Yes, it will drop the decimal point. That means it will round towards zero, so it will round down if it is positive, but it will round up if it is negative.

    See §5.1.3 in the JLS:

    Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3).