如何使用Java将float转换为int [英] How to convert float to int with Java

查看:1655
本文介绍了如何使用Java将float转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了下面这行代码将float转换为int,但是并不准确:

  float A = 8.61f; 
int b;

b =(int)a;

结果是: 8 a = -7.65f $ b> ,结果是: -7 (它应该是 -8



使用 Math.round()方法是最好的方法吗? 会将浮点四舍五入到最接近的整数。


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 ?

解决方案

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

这篇关于如何使用Java将float转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆