Floating-Point Numbers


You are already familiar with the primitive-type int, representing integer values. In addition to integer numerics, Java supports IEEE 754 32-bit single precision binary floating point format numbers, also known as float points, or floats. Java also supports 64-bit double precision floats, also known as doubles.

Table 5.1 lists the types, the range of values that they support and some examples.

Table 5.1. Floating-Point Precision Types

Type

Range

Example Literals

float

1.40239846e -45f to 3.40282347e + 38f

6.07f 6F 7.0f 7.0f 1.8e5f

double

4.94065645841246544e -324 to 1.79769313486231570e +308

1440.0 6 3.2545e7 32D 0d


Any numeric literal with a decimal point or any numeric literal with a suffix of f, F, d, or D, is by definition a floating-point number.

Float and double literals may also use scientific notation. Any number with an e or E in the middle is by definition a floating-point number. The double numeric literal 1.2e6 represents 1.2 times 10 to the 6th power, or 1.2x106 in standard mathematical notation.

If you do not supply a suffix for a floating-point number, it is by default a double precision float. In other words, you must supply an F or f suffix to produce a single precision float literal. In Agile Java, I will prefer the use of double over float due to its higher precision and the fact that I need not supply a suffix.

Realize, though, that floating-point numbers are approximations of real numbers based on bit patterns. It is not possible to represent all real numbers, since there are an infinite amount of real numbers and only a finite set of possible representations in either 32- or 64-bit precision floats. This means that most real numbers have only an approximate floating-point representation.

For example, if you execute the following line of code:

 System.out.println("value = " + (3 * 0.3)); 

the output will be:

 value = 0.8999999999999999 

and not the expected value 0.9.

If you use floating-point numbers, you must be prepared to deal with these inaccuracies by using rounding techniques. Another solution is to use the Java class BigDecimal to represent numbers with fractional parts. Agile Java presents BigDecimal in Lesson 10.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net