Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java correct way convert/cast object to Double

I need to convert Object o to Double. Is the correct way to convert it to String first?

like image 722
user710818 Avatar asked Sep 02 '25 17:09

user710818


2 Answers

new Double(object.toString());

But it seems weird to me that you're going from an Object to a 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.

like image 114
RichW Avatar answered Sep 04 '25 07:09

RichW


If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.

Double asDouble(Object o) {
    Double val = null;
    if (o instanceof Number) {
        val = ((Number) o).doubleValue();
    }
    return val;
}
like image 31
Dave B Avatar answered Sep 04 '25 06:09

Dave B