How to Add Buttons and Text to Your JavaFX Project
Syntactical Errors in Java
Understanding Classes and Objects

Floating-Point Data Types in Java

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

Java has two primitive types for floating-point numbers:

  • float: Uses 4 bytes

  • 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.

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 the literal as an integer. Then, when it sees that you’re trying to assign the integer literal to a double variable, the compiler converts the integer to a double value. This avoidable conversion step uses some precious processing time.

To save that time, you can add an F or D suffix to a floating-point literal to indicate whether the literal itself is of type float or double. For example:

float value1 = 199.33F;
double value2 = 200495.995D;

If you omit the suffix, D is assumed. As a result, you can usually omit the D suffix for double literals.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Android App Troubleshooting: Error Message — R Cannot be Resolved
Catching Errors in Java
How to Create Your Own Packages in Java
Java: Executing Tasks Until Complete
How to Create GUI Applications with Java Classes