I used the following line to convert float to int, but it's not as accurate as I'd like:
float a=8.61f;
int b;
b=(int)a;
The result is : 8
(It should be 9
)
When a = -7.65f
, the result is : -7
(It should be -8
)
What's the best way to do it ?
This question is related to
java
floating-point
int
If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.
First way is floor rounding the float value:
float myFloat = 3.14f;
int myInteger = (int)myFloat;
The output of this code will be 3, even if the myFloat value is closer to 4.
The second way is ceil rounding the float value:
float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);
The output of this code will be 4, because the rounding mode is always looking for the highest value.
Math.round(value)
round the value to the nearest whole number.
Use
1) b=(int)(Math.round(a));
2) a=Math.round(a);
b=(int)a;
As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.
Not dependent on Java Math.round() types
Use Math.round(value)
then after type cast it to integer.
float a = 8.61f;
int b = (int)Math.round(a);
Math.round also returns an integer value, so you don't need to typecast.
int b = Math.round(float a);
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 = -3
note: 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 = -2
ceil/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.
Source: Stackoverflow.com