开发者

Java parse a number in exponential notation

I am trying to do a conversion of a String to integer for which I get a NumberFormatException. The reason is pretty obvious. But I need a workaround here. Following is the sample code.

public class NumberFormatTest {
 public static void main(String[] args) {
  String num = "9.18E+09";
  try{
   long val = Long.valueOf(num);
  }catch(NumberFormatException ne){
   //Tr开发者_开发问答y to convert the value to 9180000000 here
  }
 }
}

I need the logic that goes in the comment section, a generic one would be nice. Thanks.


Use Double.valueOf() and cast the result to long:

Double.valueOf("9.18E+09").longValue()


BigDecimal bd = new BigDecimal("9.18E+09");
long val = bd.longValue();

But this adds overhead, which is not needed with smaller numbers. For numbers that are representable in long, use Joachim Sauer's solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜