Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does double to int cast work in Java

I am new to Java, and wondering how does double to int cast work ? I understand that it's simple for long to int by taking the low 32 bits, but what about double (64 bits) to int (32 bits) ? those 64 bits from double in binary is in Double-precision floating-point format (Mantissa), so how does it convert to int internally ?

like image 641
peter Avatar asked Sep 20 '12 14:09

peter


People also ask

How does Casting a double to an int work?

double to int - Math.It accepts a double value and converts into the nearest long value by adding 0.5 and truncating decimal points. Once you got the long value, you can cast it to int again, as shown below: int a = (int) Math.

Can a double be cast into an int?

#1) Typecasting In this way of conversion, double is typecast to int by assigning double value to an int variable. Here, Java primitive type double is bigger in size than data type int. Thus, this typecasting is called 'down-casting' as we are converting bigger data type values to the comparatively smaller data type.

How does int cast work in Java?

In Java when you cast you are changing the “shape” (or type) of the variable. The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. For example, (double) 1/3 will give a double result instead of an int one.


1 Answers

It's all documented in section 5.1.3 of the JLS.

In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:

If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.

  • 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). Then there are two cases:

    • If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.

    • Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.

  • Otherwise, one of the following two cases must be true:

    • The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

    • The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

(The second step here is irrelevant, when T is int.)

In most cases I'd expect this to be implemented using hardware support - converting floating point numbers to integers is something which is usually handled by CPUs.

like image 197
Jon Skeet Avatar answered Oct 05 '22 04:10

Jon Skeet