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.
Videos
You should look at ceiling rounding up in java's math packages: Math.ceil
EDIT: Added the javadoc for Math.ceil. It may be worth reading all the method in Math.
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil%28double%29
public static double ceil(double a)Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases:
- If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
- If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
- If the argument value is less than zero but greater than -1.0, then the result is negative zero.
Note that the value of
Math.ceil(x)is exactly the value of-Math.floor(-x).
try this
float a = 4.5f;
int d = (int) Math.ceil(a);
System.out.println(d);