ProgrammingJava Developer

What are the peculiarities of working with float and double data types in Java? When to use each of them and what pitfalls may arise when working with floating-point numbers?

Pass interviews with Hintsage AI assistant

Answer

In Java, there are two main types for representing floating-point numbers: float (32 bits) and double (64 bits). float is less precise and takes up less memory, while double provides greater precision and is the preferred default type for floating-point numbers.

  • When to use float: if there are very strict memory requirements (for example, a large number of numbers in an array, resource-constrained device).
  • When to use double: almost always, if there are no special constraints, as double provides better precision.

Important features:

  • Floating-point operations can lead to accumulated rounding errors.
  • Never use == for comparing float/double, use comparison with precision instead.

Example of comparison with delta:

public class DoubleComparison { public static void main(String[] args) { double a = 0.1 + 0.2; double b = 0.3; double epsilon = 1e-10; if (Math.abs(a - b) < epsilon) { System.out.println("Equal considering the precision"); } else { System.out.println("Not equal"); } } }

Trick question

Question: What will the following code output?

System.out.println(0.1 + 0.2 == 0.3);

Answer: This code will output false, because the result of the sum 0.1 + 0.2 in the IEEE 754 binary format is not exactly equal to 0.3 due to the peculiarities of storing decimal fractions in float and double types.

Examples of real errors due to lack of knowledge of this topic


Story

On a large financial project, money counters used the double type. In practice, small operations often led to accumulated rounding errors, resulting in final sums differing by a few cents. The issue was solved by replacing double with BigDecimal.


Story

In a game engine, a float array was used to store object coordinates in a world with large values. When moving over long distances, the accuracy of object positioning began to degrade, resulting in "trembling" objects on the screen. Replacing float with double and centering the coordinates helped resolve the issue.


Story

In a statistical analysis program, double values were compared using the == operator and unexpected numbers of "mismatches" were encountered. After switching to delta comparison, the program logic worked correctly.