Java Reference
In-Depth Information
If you run into this problem, the simplest remedy is to use the long type. Advanced
Topic 4.1 shows you how to use the arbitary-precision BigInteger type in the
unlikely event that even the long type overflows.
Overflow is not usually a problem for double-precision floating-point numbers. The
double type has a range of about 10 308 and about 15 significant digits. However,
you want to avoid the float typeȌit has less than 7 significant digits. (Some
programmers use float to save on memory if they need to store a huge set of
numbers that do not require much precision.)
Rounding errors are a more serious issue with floating-point values. Rounding errors
can occur when you convert between binary and decimal numbers, or between
integers and floating-point numbers. When a value cannot be converted exactly, it is
rounded to the nearest match. Consider this example:
Rounding errors occur when an exact conversion between numbers is not possible.
double f = 4.35;
System.out.println(100 * f); // Prints 434.99999999999994
This problem is caused because computers represent numbers in the binary number
system. In the binary number system, there is no exact representation of the fraction
1/10, just as there is no exact representation of the fraction 1/3 = 0.33333 in the
decimal number system. (See Advanced Topic 4.2 for more information.)
For this reason, the double type is not appropriate for financial calculations. In this
topic, we will continue to use double values for bank balances and othe r financial
quantities so that we keep our programs as simple as possible. However , professional
programs need to use the BigDecimal type for this purposeȌsee Advanced Topic
4.1 .
135
136
In Java, it is legal to assign an integer value to a floating-point variable:
int dollars = 100;
double balance = dollars; // OK
But the opposite assignment is an error: You cannot assign a floating-point expression
to an integer variable.
Search WWH ::




Custom Search