DEV Community

Cover image for Understanding float and double in Java
Ricardo Caselati
Ricardo Caselati

Posted on

Understanding float and double in Java

When diving deeper into Java’s data types, it's essential to understand float and double. These are floating-point data types used for real numbers, allowing for precision in handling both tiny and massive values.

  • float: Compact and efficient, perfect for lightweight tasks. It requires adding an f at the end of the number to explicitly mark it as a float.
  • double: As the name suggests, it has double the precision of float, making it ideal for complex calculations and scenarios where precision matters.

Key Points:

  1. Java interprets a number like 1.5 as double by default. To use a float, append an f (e.g., 1.5f).
  2. float stores fewer decimal places than double, which is better for high-precision needs.

Example with float:

public class FloatExample {
    public static void main(String[] args) {
        float numA = -101.23f;
        float numB = 2.356f;
        System.out.println(numA + numB); // Output: -98.874
    }
}
Enter fullscreen mode Exit fullscreen mode

Example with double:

public class DoubleExample {
    public static void main(String[] args) {
        double valueOne = 0.5; // Implicitly a double
        double valueTwo = 0.5d; // Explicitly a double
        double valueThree = 0.123456789; // High precision
        System.out.println(valueOne);    // Output: 0.5
        System.out.println(valueTwo);    // Output: 0.5
        System.out.println(valueThree);  // Output: 0.123456789
    }
}
Enter fullscreen mode Exit fullscreen mode

Why Choose One Over the Other?

  • Choose float when memory is limited and calculations are less precise.
  • Choose double for scientific calculations or applications needing high precision.

Top comments (0)