37

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){
   //Try to convert the value to 9180000000 here
  }
 }
}

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
bragboy
  • 34,892
  • 30
  • 114
  • 171
  • 1
    @CPerkins: I don't think it's a duplicate as this question seems to be only about the numeric question, while the linked one is about each part of the notation. – Joachim Sauer Apr 27 '10 at 14:48

2 Answers2

95

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

Double.valueOf("9.18E+09").longValue()
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • Nice solution.. Thank you. cant accept the answer now, have to wait for 7 more minutes. :) – bragboy Apr 27 '10 at 14:46
  • 7
    Old post, but if you want to enforce exact long range (no truncation) and avoid rounding errors, use `new BigDecimal(numberString).longValueExact()` – Matt Byrne May 08 '14 at 05:58
14
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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140