How to convert float to int with Java
To convert a float
to an int
in Java, you can use the (int)
type cast operator. The (int)
operator will truncate the decimal part of the float
value and convert it to an int
.
Here's an example of how you can use the (int)
operator to convert a float
to an int
:
public class Main {
public static void main(String[] args) {
float f = 123.45f;
int x = (int) f;
System.out.println(x); // prints 123
}
}
In this example, the f
variable is a float
with the value 123.45f
. The (int)
operator is used to convert the float
to an int
, and the result is assigned to the x
variable. The x
variable will have the value 123
, since the decimal part of the float
value is truncated.
I hope this helps! Let me know if you have any questions.