I'm pulling an int from a mongo cursor object like so:
DBObject mapObj = cursor.next();
int autostart = (int) (double) (Double) mapObj.get("autostart");
It seems strange that I have to triple cast to get it to an integer, is there a better way?
I think what you are really looking for is something like this:
DBObject mapObj = cursor.next();
int autostart = ((Number) mapObj.get("autostart")).intValue();
No conversion to a string and it is safe if the value gets converted to a Double or Long (with the potential loss of precision) from the original Integer value. Double, Long and Integer all extend Number.
HTH Rob
Also, you can do it this way:
int autostart = Integer.valueOf(mapObj.get("autostart").toString());
Regarding your last comment:
If you want double, use this:
int autostart = Double.valueOf(mapObj.get("autostart").toString());
But what is the sense in that? You could rather have :
double autostart = Double.valueOf(mapObj.get("autostart").toString());
Yep, you only need one cast.
double autostart = (Double) mapObj.get("autostart");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With