Joel
Joel

Reputation: 1690

Reading mixed long and double into same variable

I am reading data from an API in Java where the value can be long (ex. 0, 3, 45, etc) or double (Ex. 0.3, 4.6, 26.8, etc).

The data is coming from JSON and read in as JSONObject. Depending on what data is coming in, it gives one error or the other. ie. java.lang.Long cannot be cast to java.lang.Double or vice versa.

Double myvariable = (Double) ((JSONObject)parentVariable.get("Index"))

How do I allow it to accept both types and convert to double?

Upvotes: 0

Views: 306

Answers (1)

River
River

Reputation: 9093

If all else fails, you can always use the parent class Number and it's method doubleValue().

double myvariable = ((Number) (JSONObject)parentVariable.get("Index"))).doubleValue()

Upvotes: 3

Related Questions