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.
To get the exponential value of a number in Java, we use the java. lang. Math. exp() method.
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.
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.
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