Now suppose we have a measurement in centimeters, and we want to round it off to the nearest inch. It is tempting to write:
inch = cm / CM_PER_INCH; // syntax error
But the result is an error – you get something like, “Bad types in assignment: from double to int.” The problem is that the value on the right is floating-point, and the variable on the left is an integer.
The simplest way to convert a floating-point value to an integer is to use a type cast, so called because it molds or “casts” a value from one type to another. The syntax for type casting is to put the name of the type in parentheses and use it as an operator.
double pi = 3.14159; int x = (int) pi;
(int) operator has the effect of converting what follows into an integer. In this example,
x gets the value
3. Like integer division, converting to an integer always rounds toward zero, even if the fraction part is
-0.999999). In other words, it simply throws away the fractional part.
Type casting takes precedence over arithmetic operations. In this example, the value of
pi gets converted to an integer before the multiplication. So the result is 60.0, not 62.0.
double pi = 3.14159; double x = (int) pi * 20.0;
Keeping that in mind, here’s how we can convert a measurement in centimeters to inches:
inch = (int) (cm / CM_PER_INCH); System.out.printf("%f cm = %d in\n", cent, inch);
The parentheses after the cast operator require the division to happen before the type cast. And the result is rounded toward zero; we will see in the next chapter how to round floating-point numbers to the closest integer.