简体   繁体   English

将float转换为int

[英]Converting float to int

I come from Python background and taking a dive into Java world. 我来自Python背景,并涉足Java世界。 I am trying to convert Float to int in Java. 我正在尝试将Float转换为Java中的int。 Something we do like this in Python int_var = int(float_var) 我们在Python中这样做的事情int_var = int(float_var)


public class p1 {
    public static void main(String args[]) {
        Integer a = new Integer(5);
        Float b;
        b = new Float(3.14);
        a = (int)b;
        System.out.println(a);
    }
}
Yields the following error - 产生以下错误-
 p1.java:7: error: inconvertible types a = (int)b; ^ required: int found: Float 1 error 

你可以做到

a = b.intValue()

That's one of the annoying things in Java. 这是Java中令人讨厌的事情之一。 Fix your problem with this: 解决此问题:

a = (int)(float)b;

Unboxing will require that you cast from Float to float and then to int 取消装箱要求您从Floatfloat然后转换为int

Use primitives types, and you will be fine: 使用基本类型,您将可以:

int a = 5;
float b = 3.14f;  // 3.14 is by default double. 3.14f is float.

a = (int)b;

The reason it didn't work with Wrappers is those types are non-covariant, and thus are incompatible. 它不适用于Wrappers的原因是那些类型是非协变的,因此不兼容。


And if you are using Integer types (Which you really don't need here), then you should not create Wrapper type objects using new . 而且,如果您使用的是Integer类型(此处实际上并不需要),则不应使用new创建Wrapper类型的对象。 Just make use of auto-boxing feature: 只需利用自动装箱功能:

Integer a = 5;  // instead of `new Integer(5);`

the above assignment works after Java 1.5, performing auto-boxing from int primitive to Integer wrapper. 上面的分配在Java 1.5之后起作用,执行从int原语到Integer包装器的自动装箱。 It also enables JVM to use cached Integer literals if available, thus preventing creation of unnecessary objects. 它还使JVM可以使用缓存的Integer文字(如果可用),从而防止创建不必要的对象。

Since you're using boxed primitive, a = b.intValue(); 由于您使用的是盒装原语,因此a = b.intValue(); should suit your needs. 应该适合您的需求。

 float a =10.0f;
 int k=(int)a;

使用此代码
a = b.intValue();

使用Math.round方法:

int a = Math.round(b);

for the best always use: 为获得最佳效果,请始终使用:

Math.floor(d)
Math.round(d)
Math.abs(d)

These are meant for conversions. 这些是用于转换的。

您可以简单地将Use Math.round()用作

   int a = Math.round(14.32f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM