In this tutorial, you will learn how to convert a float
value to a long
in Java. We’ll go through examples that demonstrate explicit conversion and discuss handling the decimal part of the float
during conversion.
Java – Convert float to long
Converting float to long in Java – In Java, converting a float
to a long
requires explicit casting because float
is a floating-point type, while long
is an integer type. This means that converting from float
to long
will truncate the decimal portion of the float
value.
Explicit Conversion from float to long
To convert a float
to a long
in Java, you need to explicitly cast the float
value. This conversion will truncate any decimal places and return only the whole number part.
Example of Explicit Conversion
public class FloatToLongExample {
public static void main(String[] args) {
float floatVal = 9.78f;
long longVal = (long) floatVal; // Explicit conversion from float to long
System.out.println("Float value: " + floatVal);
System.out.println("Long value after conversion: " + longVal);
}
}
Output
Float value: 9.78
Long value after conversion: 9
In this example, the float
value 9.78
is converted to a long
by truncating the decimal portion, resulting in a value of 9
.
Alternative: Using Math.round() to Round the Value
If you want to round the float
value to the nearest integer before converting it to long
, you can use Math.round()
. This method returns a long
value with the float
rounded to the nearest whole number.
Example of Rounding Before Conversion
public class FloatToLongExample {
public static void main(String[] args) {
float floatVal = 9.78f;
long longVal = Math.round(floatVal); // Rounding and converting to long
System.out.println("Float value: " + floatVal);
System.out.println("Long value after rounding: " + longVal);
}
}
Output
Float value: 9.78
Long value after rounding: 10
Here, Math.round()
rounds 9.78
up to 10
before converting it to long
, unlike direct casting, which simply truncates the decimal part.
Conclusion
In this tutorial, you learned how to convert a float
to a long
in Java. You can use explicit casting to truncate the decimal or Math.round()
to round the value. Choose the method that best fits your use case to control how decimal parts are handled in conversions.