How can I convert float to integer in Java
18,454
Solution 1
You have in Math library function round(float a)
it's round the float to the nearest whole number.
int val = Math.round(3.6); \\ val = 4
int val2 = Math.round(3.4); \\ val2 = 3
Solution 2
It is a bit dirty but it works:
double a=3.6;
int b = (int) (a + 0.5);
See the result here
Author by
Marko Petričević
Updated on June 04, 2022Comments
-
Marko Petričević almost 2 years
I need to convert a float number into an integer.
Can Java automatically convert float number into integers? If so, do normal rounding rules apply (e.g. 3.4 gets converted to 3, but 3.6 gets converted to 4)?