The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Converting from double to int

As I mentioned, Java converts a ints to doubles automatically if necessary, because no information is lost in the translation. On the other hand, going from a double to an int requires rounding off. Java doesn't perform this operation automatically, in order to make sure that you, as the programmer, are aware of the loss of the fractional part of the number.

The simplest way to convert a floating-point value to an integer is to use a typecast. Typecasting is so called because it allows you to take a value that belongs to one type and "cast" it into another type (in the sense of molding or reforming, not throwing).

Unfortunately, the syntax for typecasting is ugly: you put the name of the type in parentheses and use it as an operator. For example,

    int x = (int) Math.PI;

The (int) operator has the effect of converting what follows into an integer, so x gets the value 3.

Typecasting takes precedence over arithmetic operations, so in the following example, the value of PI gets converted to an integer first, and the result is 60, not 62.

    int x = (int) Math.PI * 20.0;

Converting to an integer always rounds down, even if the fraction part is 0.99999999.

These two properties (precedence and rounding) can make typecasting awkward.

Last Update: 2011-01-24