Java Reference
In-Depth Information
double a = 1.998899;
long b = Math.round(a);
//b=2
The rint() method also rounds the double operand to an integer but re-
turns the result as a double. The methods floor() and ceil() of
java.lang.Math allow obtaining the largest and the smallest integers of a
double value. Both methods return a double integer, which can then be
typecast into one of the integer formats. These methods are described in
Chapter 23.
Integer and fractional parts
Rational and irrational numbers must often be separated into their integer
and fractional parts. Obtaining the integer part of a floating-point value is
easily accomplished by typecasting. Note that the round() method cannot
be used in this case since you actuallywant to chop off the integer part. The
fractional part can be obtained by subtracting the integer part from the
original number. The following program shows the operations.
// Java for Engineers
// Filename: IntFrac
// Reference: Chapter 24
// Description:
//
Obtaining the integer and fractional parts
// Requires:
// Keyin class in current directory
import java.lang.*;
class IntFrac
{
public static void main(String[] args)
{
double num;
long iPart;
double fPart;
// Get user input
num = Keyin.inDouble(“Enter a floating-point value: ”);
iPart = (int)num;
fPart = num - iPart;
System.out.println(“Integer part=”+iPart);
System.out.println(“Fractional part=”+fPart);
}
}
On the Web
The program IntFrac.java is found in the Chapter 24 folder at
www.crcpress.com .
Search WWH ::




Custom Search