In this tutorial, you will learn how to convert a double value to a float in Java. We’ll cover explicit casting, potential precision loss, and examples to help you understand the conversion process.

Java – Convert double to float

Converting double to float in Java – In Java, converting a double to a float requires explicit casting because double has a larger precision and range than float. This conversion can lead to precision loss if the double value exceeds the precision that a float can represent.

Explicit Conversion from double to float

To convert a double to a float in Java, you need to use an explicit cast. This tells the compiler that you understand the potential precision loss and that you intend to perform the conversion.

Example of Explicit Conversion

</>
Copy
public class DoubleToFloatExample {

    public static void main(String[] args) {
        double doubleVal = 9.123456789;
        float floatVal = (float) doubleVal; // Explicit conversion from double to float
        System.out.println("Double value: " + doubleVal);
        System.out.println("Float value after conversion: " + floatVal);
    }
}

Output

Double value: 9.123456789
Float value after conversion: 9.123457

In this example, the double value 9.123456789 is explicitly cast to a float, which results in a loss of precision beyond 6 decimal places.

Precision Loss with Large Double Values

If the double value is too large or precise for a float to handle, the conversion will result in precision loss. This happens because float can only represent approximately 6-7 significant decimal digits, while double can represent up to 15-16.

Example Demonstrating Precision Loss

</>
Copy
public class DoubleToFloatExample {

    public static void main(String[] args) {
        double doubleVal = 123456789.987654321;
        float floatVal = (float) doubleVal; // Explicit conversion
        System.out.println("Double value: " + doubleVal);
        System.out.println("Float value after conversion: " + floatVal);
    }
}

Output

Double value: 123456789.987654321
Float value after conversion: 1.23456792E8

In this example, the large double value loses precision after conversion to float, displaying only as 1.23456792E8.

Conclusion

Converting a double to a float in Java requires explicit casting, and it may lead to precision loss, especially with large or highly precise values. Be mindful of the limitations of float and consider using double if high precision is necessary.