简体   繁体   English

Java正确方法将对象转换/转换为Double

[英]Java correct way convert/cast object to Double

I need to convert Object o to Double.我需要将 Object o 转换为 Double。 Is the correct way to convert it to String first?首先将其转换为字符串的正确方法是什么?

new Double(object.toString());

But it seems weird to me that you're going from an Object to a Double.但对我来说,你从 Object 变成 Double 似乎很奇怪。 You should have a better idea what class of object you're starting with before attempting a conversion.在尝试转换之前,您应该更好地了解从哪一类对象开始。 You might have a bit of a code quality problem there.您可能在那里遇到了一些代码质量问题。

Note that this is a conversion, not casting.请注意,这是一种转换,而不是强制转换。

If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.如果您的对象代表一个数字,例如一个整数,您可以将它转换为一个数字,然后调用 doubleValue() 方法。

Double asDouble(Object o) {
    Double val = null;
    if (o instanceof Number) {
        val = ((Number) o).doubleValue();
    }
    return val;
}

You can't cast an object to a Double if the object is not a Double.你不能施放对象为Double如果对象是不是双。

Check out the API .查看API

particularly note特别注意

valueOf(double d);

and

valueOf(String s);

Those methods give you a way of getting a Double instance from a String or double primitive.这些方法为您提供了一种从 String 或 double 基元获取Double实例的方法。 (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double. (也不是构造函数;阅读文档以了解它们是如何工作的)您尝试自然转换的对象必须为您提供一些可以转换为双精度的对象。

Finally, keep in mind that Double instances are immutable -- once created you can't change them.最后,请记住Double实例是不可变的——一旦创建就无法更改它们。

You can use the instanceof operator to test to see if it is a double prior to casting.您可以在转换之前使用 instanceof 运算符来测试它是否为双精度值。 You can then safely cast it to a double.然后您可以安全地将其转换为双精度值。 In addition you can test it against other known types (eg Integer) and then coerce them into a double manually if desired.此外,您可以针对其他已知类型(例如整数)对其进行测试,然后根据需要手动将它们强制转换为双精度型。

    Double d = null;
    if (obj instanceof Double) {
        d = (Double) obj;
    }

In Java version prior to 1.7 you cannot cast object to primitive type在 1.7 之前的 Java 版本中,您不能将对象强制转换为原始类型

double d = (double) obj;

You can cast an Object to a Double just fine您可以将 Object 转换为 Double 就好了

Double d = (Double) obj;

Beware, it can throw a ClassCastException if your object isn't a Double请注意,如果您的对象不是 Double,它可能会抛出 ClassCastException



Also worth mentioning -- if you were forced to use an older Java version prior to 1.5, and you are trying to use Collections, you won't be able to parameterize the collection with a type such as Double .还值得一提的是——如果您被迫使用 1.5 之前的旧 Java 版本,并且您正在尝试使用 Collections,您将无法使用诸如Double类的类型来参数化集合。

You'll have to manually " box " to the class Double when adding new items, and " unbox " to the primitive double by parsing and casting, doing something like this:添加新项目时,您必须手动“装箱”到类Double ,并通过解析和转换将“取消装箱”到原始double精度型,执行如下操作:

LinkedList lameOldList = new LinkedList();
lameOldList.add( new Double(1.2) );
lameOldList.add( new Double(3.4) );
lameOldList.add( new Double(5.6) );

double total = 0.0;
for (int i = 0, len = lameOldList.size(); i < len; i++) {
  total += Double.valueOf( (Double)lameOldList.get(i) );
}


The old-school list will contain only type Object and so has to be cast to Double .老式列表将只包含Object类型,因此必须转换为Double

Also, you won't be able to iterate through the list with an enhanced-for-loop in early Java versions -- only with a for-loop.此外,您将无法在早期 Java 版本中使用增强的 for 循环遍历列表——只能使用 for 循环。

I tried this and it worked:我试过了,它奏效了:

Object obj = 10;
String str = obj.toString(); 
double d = Double.valueOf(str).doubleValue();

Tried all these methods for conversion ->尝试了所有这些转换方法 ->

obj2Double

    public static void main(String[] args) {

    Object myObj = 10.101;
    System.out.println("Cast to Double: "+((Double)myObj)+10.99);   //concates

    Double d1 = new Double(myObj.toString());
    System.out.println("new Object String - Cast to Double: "+(d1+10.99));  //works

    double d3 = (double) myObj;
    System.out.println("new Object - Cast to Double: "+(d3+10.99));     //works

    double d4 = Double.valueOf((Double)myObj);
    System.out.println("Double.valueOf(): "+(d4+10.99));        //works

    double d5 = ((Number) myObj).doubleValue();
    System.out.println("Cast to Number and call doubleValue(): "+(d5+10.99));       //works

    double d2= Double.parseDouble((String) myObj);
    System.out.println("Cast to String to cast to Double: "+(d2+10));       //works
}

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

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