如何使用Java将float转换为int

本文翻译自: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()类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值