How to convert float to int with Java

Frank picture Frank · Aug 18, 2009 · Viewed 671.5k times · Source

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 ?

Answer

tw39124 picture tw39124 · Aug 18, 2009

Using Math.round() will round the float to the nearest integer.