In this tutorial, you will learn how to convert a long
value to a float
in Java. We’ll explore both implicit and explicit conversion methods with examples to help you understand how the conversion works.
Java – Convert long to float
Converting long to float in Java – In Java, converting a long
to a float
can be done implicitly because float
can represent a wider range of numbers than long
, although with less precision. However, due to the limitations of floating-point representation, some precision might be lost during the conversion.
Implicit Conversion from long to float
Java allows implicit conversion (widening conversion) from long
to float
. This means you can assign a long
value directly to a float
variable without any explicit casting.
Example of Implicit Conversion
public class LongToFloatExample {
public static void main(String[] args) {
long longVal = 100000L;
float floatVal = longVal; // Implicit conversion from long to float
System.out.println("Long value: " + longVal);
System.out.println("Float value after conversion: " + floatVal);
}
}
Output
Long value: 100000
Float value after conversion: 100000.0
In this example, the long
value 100000
is implicitly converted to a float
without any issues.
Potential Precision Loss
While converting from long
to float
is straightforward, it’s important to note that float
has less precision than long
. Large long
values may lose precision when converted to float
.
Example Demonstrating Precision Loss
public class LongToFloatExample {
public static void main(String[] args) {
long longVal = 123456789012345L;
float floatVal = longVal; // Implicit conversion
System.out.println("Long value: " + longVal);
System.out.println("Float value after conversion: " + floatVal);
}
}
Output
Long value: 123456789012345
Float value after conversion: 1.23456792E14
In this example, the original long
value is 123456789012345
, but the float
representation is 1.23456792E14
. The precision is lost beyond a certain point due to the limitations of the float
type.
Explicit Conversion from long to float
Even though implicit conversion is allowed, you can also perform an explicit cast to make the conversion clear in your code.
Example of Explicit Conversion
public class LongToFloatExample {
public static void main(String[] args) {
long longVal = 100000L;
float floatVal = (float) longVal; // Explicit conversion from long to float
System.out.println("Long value: " + longVal);
System.out.println("Float value after explicit conversion: " + floatVal);
}
}
The output will be the same as with implicit conversion, but the explicit cast makes it clear that a conversion is happening.
Conclusion
Converting a long
to a float
in Java is straightforward due to implicit widening conversion. However, be cautious of potential precision loss when dealing with large numbers. If precision is critical, consider using double
or BigDecimal
for more accurate representations.