简体   繁体   English

在 Java 中转换 float int

[英]Convert float int in Java

I'm new to Java and I don't have a clue how to convert given variable to int.我是 Java 的新手,我不知道如何将给定变量转换为 int。 I've done this:我已经这样做了:

public class Ulamek<T> {
    private T licznik;
    private T mianownik;

    public Ulamek(T licznik, T mianownik) {
        this.licznik = licznik;
        this.mianownik = mianownik;
    }

And I want variables licznik and mianownik always to be type of int even if I create an object Ulamek with float or double.而且我希望变量licznikmianownik始终是int类型,即使我创建了一个带有浮点或双精度的 object Ulamek Is there a way to convert them or any other way to do this?有没有办法转换它们或任何其他方式来做到这一点? I have to do this with the <T> in public class Ulamek<T> .我必须使用public class Ulamek<T>中的<T>来执行此操作。

You can make the class non-generic and use method overloading to support instantiating the class with different types.您可以使 class 成为非泛型并使用方法重载来支持用不同类型实例化 class。

Example例子

public class Ulamek {
    private int licznik;
    private int mianownik;

    public Ulamek(int licznik, int mianownik) {
        this.licznik = licznik;
        this.mianownik = mianownik;
    }

    public Ulamek(double licznik, double mianownik) {
        this.licznik = (int)licznik;
        this.mianownik = (int)mianownik;
    }
}

Here is one possible approach.这是一种可能的方法。

    public static <T> int value(T v) {
        int k;
        if (v instanceof Double) {
            k = ((Double)v).intValue();
            return k;
        }
        return -1; // error, only valid for positive values of v.
    }

You would need to structure this around exception handling if v is any Number since any value of k you return could not accurately relate an error.如果 v 是任何Number ,则您需要围绕异常处理来构建它,因为您返回的任何k值都无法准确地关联错误。

If v is a primitive, then generics won't be involved and just do a simple cast to int如果 v 是一个原语,那么 generics 将不参与,只需简单地转换为int

double f  = 4.;
int i = (int)f;

It looks like you're aiming to create a method (in this case it's a constructor, but the principle applies to methods in general) that accepts any type of number and then convert those numbers to an integer value and store those.看起来您的目标是创建一个接受任何类型数字的方法(在本例中是构造函数,但原则适用于一般方法),然后将这些数字转换为 integer 值并存储这些值。

If:如果:

  • you want to allow any numeric type and want to avoid method overloading,您希望允许任何数字类型并希望避免方法重载,
  • you accept that the numbers may get truncated, rounded or even overflow to a negative value (for instance when you provide a long value that is larger than Integer.MAX_VALUE )您接受数字可能会被截断、四舍五入甚至溢出为负值(例如,当您提供大于Integer.MAX_VALUElong值时)
  • and you want to avoid having to perform the type conversion when invoking your constructor (therefore having int s as an argument may not be an option in your specific case).并且您希望避免在调用构造函数时执行类型转换(因此在您的特定情况下,将int s 作为参数可能不是一个选项)。

You could use an implementation that leverages Java autoboxing and the fact that these boxed numerical types all extend the same base class : Number .您可以使用利用 Java 自动装箱的实现以及这些装箱数字类型都扩展相同的基础 class : Number的事实。 Therefore you could write:因此你可以写:

public class Ulamek {
    private int licznik;
    private int mianownik;

    public Ulamek(Number licznik, Number mianownik) {
        this.licznik = Objects
                .requireNonNull(licznik, "licznik cannot be null")
                .intValue();
        this.mianownik = Objects
                .requireNonNull(mianownik, "mianownik cannot be null")
                .intValue();
    }
}

No need for generic type parameters.不需要泛型类型参数。

Note that I added an explicit requireNonNull there.请注意,我在那里添加了一个明确的requireNonNull You didn't specify how to deal with null values, also your target data type ( int ) doesn't have a representation for null .您没有指定如何处理null值,您的目标数据类型( int )也没有null的表示。 Therefore the safe thing to assume is that null is not acceptable here.因此可以安全地假设null在这里是不可接受的。

Now you could write:现在你可以写:

var a = new Ulamek(42, 43); // int
var b = new Ulamek(42.0, 43.0); // double
var c = new Ulamek(42l, 43l); // long
var d = new Ulamek(new BigDecimal(42.0), new BigDecimal(43.0));

Using this approach, adding range checks before assigning the integer values could prove a bit more challenging should you require those.使用这种方法,如果您需要,在分配 integer 值之前添加范围检查可能会更具挑战性。

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

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