本文翻譯自: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 be 9
) 結果是: 8
(應該是9
)
When a = -7.65f
, the result is : -7
(It should be -8
) 當a = -7.65f
,結果是: -7
(應該是-8
)
What's the best way to do it ? 最好的方法是什麼?
#1樓
參考:https://stackoom.com/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樓
Use Math.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()類型