In the article on Java Integer Arithmetic, we showed how Java performs arithmetic with integer values. We now show how it is done with floating-point numbers.
In Java, double to int (and int to double) conversions are sometimes necessary. For example, we may calculate a percentage but are interested only in the whole number part of the result. For instance, the result may be 64.37% but we don't care about the fraction. Our natural instinct is to assign the double value to an int variable.
However, Java does not let us assign a floating-point value (float or double) directly to an integer variable (byte, short, int or long).
For example, consider:
int n = 987.654321; //cannot assign double to int
long m = 3.24f; //cannot assign float to long
None of these statements is valid in Java. We can use a cast to make them valid, as in:
int n = (int) 987.654321;
long m = (long) 3.24f;
Now, 987 is assigned to n and 3 is assigned to m.
When we assign a floating-point value to an integer type, the fractional part, if any, is dropped (not rounded) and the resulting integer value is assigned. It is up to us to ensure that the integer obtained is small enough to fit in the integer type. If not, the resulting value is unpredictable.
For example, the largest byte value is 127. The statement
byte b = (byte) 300.75;
is valid and will attempt to store the value 300 in the byte variable b. Since this is too big to fit in b, the value assigned is unpredictable. In this case, the value assigned is 44.
As another example, the statement
short s = (short) 65585.36;
will store 49 in s; 65585 is too big to fit in a short variable. Here, the low-order 16 bits of 65585 (which happens to be 49) is stored in s.
Suppose the double variable d has the value 987.654321. If we want the rounded value of d (988) stored in the int variable n, we could do this with
n = (int) (d + 0.5);
If the first digit after the point in d is 5 or more, adding 0.5 would add 1 to the whole number part. If the first digit after the point is less than 5, adding 0.5 would not change the whole number part.
For example, if d is 245.75, adding 0.5 would give 246.25 and 246 would be assigned to n. But if d were 245.49, adding 0.5 would give 245.99 and 245 would be assigned to n.