Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parse a number in exponential notation

Tags:

java

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.

like image 353
bragboy Avatar asked Apr 27 '10 14:04

bragboy


People also ask

How do you write a number in exponential form in Java?

To get the exponential value of a number in Java, we use the java. lang. Math. exp() method.

Which among the following is a scientific notation in Java?

The format of scientific notation in Java is exactly the same as you have learned and used in science and math classes. Remember that an uppercase 'E' or lowercase 'e' can be used to represent "10 to the power of". Scientific notation can be printed as output on the console if it passes a certain number.


2 Answers

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

Double.valueOf("9.18E+09").longValue() 
like image 181
Joachim Sauer Avatar answered Sep 21 '22 09:09

Joachim Sauer


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.

like image 34
Bozho Avatar answered Sep 20 '22 09:09

Bozho