Floating-point Data Types

Floating-point numbers are numbers that have fractional parts (usually expressed with a decimal point). You should use a floating-point type whenever you need a number with a decimal, such as 19.95 or 3.1415.

Java has two primitive types for floating-point numbers:

check.png float : Uses 4 bytes

check.png double : Uses 8 bytes

In almost all cases, you should use the double type whenever you need numbers with fractional values.

The precision of a floating-point value indicates how many significant digits the value can have following its decimal point. The precision of a float type is only about six or seven decimal digits, which isn’t sufficient for most types of calculations. If you use Java to write a payroll system, for example, you might get away with using float variables to store salaries for employees such as teachers or firefighters, but not for professional baseball players or corporate executives.

By contrast, double variables have a precision of about 15 digits, which is enough for most purposes.

tip.eps When you use a floating-point literal, you should always include a decimal point, like this:

double period = 99.0;

If you omit the decimal point, the Java compiler treats ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.