Converting from double to int

As I mentioned, Java converts 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).

The syntax for typecasting is to put the name of the type in parentheses and use it as an operator. For example,

  double pi = 3.14159;
  int x = (int) 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.0, not 62.

  double pi = 3.14159;
  double x = (int) pi * 20.0;

Converting to an integer always rounds down, even if the fraction part is 0.99999999. These behaviors (precedence and rounding) can make typecasting error-prone.