Java Reference
In-Depth Information
double balance = 13.75;
int dollars = balance; // Error
To overcome this problem, you can convert the floating-point value to an integer with
a cast:
int dollars = (int) balance;
The cast (int) converts the floating-point value balance to an integer by
discarding the fractional part. For example, if balance is 13.75, then dollars is
set to 13.
You use a cast (typeName) to convert a value to a different type.
The cast tells the compiler that you agree to information loss, in this case, to the loss
of the fractional part. You can also cast to other types, such as (float) or (byte) .
If you want to round a floating-point number to the nearest whole number, use the
Math.round method. This method returns a long integer, because large
floating-point numbers cannot be stored in an int .
Use the Math.round method to round a floating-point number to the nearest
integer.
long rounded = Math.round(balance);
If balance is 13.75, then rounded is set to 14.
S YNTAX 4.1 Cast
(typeName) expression
Example:
(int) (balance * 100)
Purpose:
To convert an expression to a different type
Search WWH ::




Custom Search