我使用下面的行来转换浮点数为int,但它不是像我想要的那样准确:

 float a=8.61f;
 int b;

 b=(int)a;

结果是:8(它应该是9)

当a = -7.65f时,结果是:-7(它应该是-8)

最好的方法是什么?


当前回答

Math.round()就足够了

int b = Math.round(a)

这样就可以了

其他回答

使用Math.round(value),然后在类型转换后将其转换为整数。

float a = 8.61f;
int b = (int)Math.round(a);

round(value)将值四舍五入到最接近的整数。

Use

1) b=(int)(Math.round(a));

2) a=Math.round(a);  
   b=(int)a;

Math.round()就足够了

int b = Math.round(a)

这样就可以了

对我来说,更简单:(int) (a +.5) // a是浮点数。返回四舍五入的值。

不依赖于Java Math.round()类型

数学。Round还返回一个整数值,因此不需要类型转换。

int b = Math.round(float a);