Java – Convert Float to Integer
In this tutorial, we shall learn how to convert a floating point value to an integer value.
Firstly, we shall go through the process of narrowing primitive conversion, where we shall manually convert a value of a higher datatype to a value of lower datatype. This process will truncate the precision part of the float value.
Secondly, we shall discuss about Math.round() function. Math.round() function returns the nearest integer to the given float value.
1. Convert float to integer using Narrow Casting
Float is a higher datatype when compared to that of Integer datatype. So, when converting a higher datatype to lower datatype, you have to manually cast integer to float. This is also called narrowing casting or narrowing primitive conversion.
To manually typecast float to integer, place the type of lower datatype keyword before higher datatype value in parenthesis.
In the following example, we have a variable f
which is of float type. We shall typecast f
to integer value and store in variable n
.
Java Program
/**
* Java Program - Convert Float to Integer
*/
public class FloatToInt {
public static void main(String[] args) {
float f = 16.8564f;
int n = (int) f;
System.out.println(n);
}
}
Output
16
Narrow Casting or Down Casting truncates the decimal part and returns only the integer part.
2. Convert float to integer using Math.round() method
Math.round() returns nearest integer value to the given floating point value.
In this example, we shall convert floating point numbers with different precision and convert to int, to understand the rounding functionality.
Java Program
/**
* Java Program - Convert Float to Integer
*/
public class FloatToInt {
public static void main(String[] args) {
float f;
int n;
f = 16.8564f;
n = Math.round(f);
System.out.println(n);
f = 16.4235f;
n = Math.round(f);
System.out.println(n);
}
}
Output
17
16
Conclusion
In this Java Tutorial, we learned how to write Java programs to convert an Float to Integer.