Using Math.round() will round the float to the nearest integer.
Using Math.round() will round the float to the nearest integer.
Actually, there are different ways to downcast float to int, depending on the result you want to achieve:
(for int i, float f)
round (the closest integer to given float)
i = Math.round(f); f = 2.0 -> i = 2 ; f = 2.22 -> i = 2 ; f = 2.68 -> i = 3 f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3note: this is, by contract, equal to
(int) Math.floor(f + 0.5f)truncate (i.e. drop everything after the decimal dot)
i = (int) f; f = 2.0 -> i = 2 ; f = 2.22 -> i = 2 ; f = 2.68 -> i = 2 f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)
i = (int) Math.ceil(f); f = 2.0 -> i = 2 ; f = 2.22 -> i = 3 ; f = 2.68 -> i = 3 f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2 i = (int) Math.floor(f); f = 2.0 -> i = 2 ; f = 2.22 -> i = 2 ; f = 2.68 -> i = 2 f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
For rounding positive values, you can also just use (int)(f + 0.5), which works exactly as Math.Round in those cases (as per doc).
You can also use Math.rint(f) to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.
See
http://mindprod.com/jgloss/round.html
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html
for more information and some examples.
(Java) Need to convert from float to integer to floats for displaying a percentage. I have tried googling, yet can't seem to wrap my head around it
Converting floats to ints
How can I convert integer into float in Java? - Stack Overflow
casting - How can I convert float to integer in Java - Stack Overflow
You just need to cast at least one of the operands to a float:
float z = (float) x / y;
or
float z = x / (float) y;
or (unnecessary)
float z = (float) x / (float) y;
// The integer I want to convert
int myInt = 100;
// Casting of integer to float
float newFloat = (float) myInt
You have in Math library function round(float a) it's round the float to the nearest whole number.
Copyint val = Math.round(3.6); \\ val = 4
int val2 = Math.round(3.4); \\ val2 = 3
It is a bit dirty but it works:
Copydouble a=3.6;
int b = (int) (a + 0.5);
See the result here