本文翻译自:How to convert float to int with Java
I used the following line to convert float to int, but it's not as accurate as I'd like:我使用以下行将float转换为int,但它并不像我想的那样准确:
float a=8.61f;int b;b=(int)a;
The result is :8
(It should be9
)结果是:8
(应该是9
)
Whena = -7.65f
, the result is :-7
(It should be-8
)当a = -7.65f
,结果是:-7
(应该是-8
)
What's the best way to do it ?最好的方法是什么?
#1楼
参考:/question/5Qzw/如何使用Java将float转换为int
#2楼
使用Math.round()
将float浮动到最接近的整数。
#3楼
Math.round(value)
round the value to the nearest whole number.Math.round(value)
将值四舍五入到最接近的整数。
Use使用
1) b=(int)(Math.round(a));2) a=Math.round(a); b=(int)a;
#4楼
UseMath.round(value)
then after type cast it to integer.使用Math.round(value)
然后在类型转换为整数后。
float a = 8.61f;int b = (int)Math.round(a);
#5楼
Math.round还返回一个整数值,因此您不需要进行类型转换。
int b = Math.round(float a);
#6楼
As to me, easier:(int) (a +.5)// a is a Float.至于我,更容易:(int)(a +.5)// a是浮点数。Return rounded value.返回舍入值。
Not dependent on Java Math.round() types不依赖于Java Math.round()类型