我正在从mongo游标对象中提取一个int,如下所示:
DBObject mapObj = cursor.next();
int autostart = (int) (double) (Double) mapObj.get("autostart");
似乎很奇怪,我需要三次转换才能将它变为整数,是否有更好的方法?
答案 0 :(得分:16)
我认为你真正想要的是这样的:
DBObject mapObj = cursor.next();
int autostart = ((Number) mapObj.get("autostart")).intValue();
不转换为字符串,如果值从原始Integer值转换为Double或Long(可能会丢失精度),则是安全的。 Double,Long和Integer都扩展了Number。
HTH Rob
答案 1 :(得分:4)
另外,你可以这样做:
int autostart = Integer.valueOf(mapObj.get("autostart").toString());
关于你的上次评论:
如果你想要加倍,请使用:
int autostart = Double.valueOf(mapObj.get("autostart").toString());
但那有什么意义呢?你宁可拥有:
double autostart = Double.valueOf(mapObj.get("autostart").toString());
答案 2 :(得分:2)
是的,你只需要一次演员。
double autostart = (Double) mapObj.get("autostart");