将float转换为int

将float转换为int

问题描述:

我来自Python背景并深入研究Java世界。
我试图在Java中将Float转换为int。我们在Python中做的事情 int_var = int(float_var)

I come from Python background and taking a dive into Java world. I am trying to convert Float to int in Java. Something we do like this in 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

使用原始类型,你会没事的:

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;

它不适用于 Wrappers 的原因是那些类型是非-covariant,因此是不兼容的。

The reason it didn't work with Wrappers is those types are non-covariant, and thus are incompatible.

如果你使用整数 types(这里你真的不需要),那么你不应该使用 new 创建Wrapper类型的对象。只需使用自动装箱功能:

And if you are using Integer types (Which you really don't need here), then you should not create Wrapper type objects using new. Just make use of auto-boxing feature:

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

上面的赋值在Java 1.5之后运行,执行自动装箱从 int 原语到整数包装器。它还使JVM能够使用缓存的Integer文字(如果可用),从而防止创建不必要的对象。

the above assignment works after Java 1.5, performing auto-boxing from int primitive to Integer wrapper. It also enables JVM to use cached Integer literals if available, thus preventing creation of unnecessary objects.