如何用Java将float转换为int

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

 float a=8.61f;
int b;


b=(int)a;

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

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

最好的方法是什么?

793656 次浏览

使用Math.round()将浮点数舍入为最接近的整数。

实际上,有不同的方法将float向下转换为int,这取决于你想要获得的结果: (对于int i, float f)

  • 整数(与给定浮点数最接近的整数)

    i = Math.round(f);
    f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  3
    f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
    

    注意:根据契约,这等于(int) Math.floor(f + 0.5f)

  • 截断(即删除小数点后的所有内容)

    i = (int) f;
    f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
    f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
  • ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)

    i = (int) Math.ceil(f);
    f =  2.0 -> i =  2 ; f =  2.22 -> i =  3 ; f =  2.68 -> i =  3
    f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
    
    i = (int) Math.floor(f);
    f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
    f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
    

For rounding positive values, you can also just use (int)(f + 0.5), which works exactly as Math.Round in those cases (as per doc).

You can also use Math.rint(f) to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.

See

http://mindprod.com/jgloss/round.html

http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

for more information and some examples.

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

使用

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


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

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

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

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

int b = Math.round(float a);

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

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

如果您想将浮点值转换为整数值,有几种方法可以实现,这取决于您想如何四舍五入浮点值。

第一种方法是浮点值的舍入:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

这段代码的输出将是3,即使myFloat值更接近4。

第二种方法是浮点值的四舍五入:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

这段代码的输出将是4,因为舍入模式总是在寻找最大值。

Math.round()就足够了

int b = Math.round(a)

这样就可以了

通过向构造函数传递float原语来实例化Float对象,然后使用您创建的Float对象返回int原语。

解释
由于数字包装器类扩展了java.lang.Number类,因此可以使用.<type>Value()方法让任何数字包装器对象返回任何其他原始的数量类型。
< / div >

步骤

  1. 创建一个Float对象
  2. 使用.intValue()方法返回一个原语int
< h3 id = " example-wbwq " > < / h3 >例子
Float mFloat = Float.valueOf(8.65f);
int i = mFloat.intValue();