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
hi all.
I've just started learning processing. I'm trying to create a 50 value float array where each value is 0.5 larger than the last, starting at zero using a for loop. I'm getting an error "cannot convert from float to int."
I'm not sure what's wrong. Any help?
float[] four = new float[50];
for(float i=0; i<four.length;i++){
four[i]=i*0.5;
}
TIA.