Java以指数表示法解析一个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2722122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:06:47  来源:igfitidea点击:

Java parse a number in exponential notation

java

提问by bragboy

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.

我正在尝试将字符串转换为整数,我得到一个NumberFormatException. 原因很明显。但我需要一个解决方法。以下是示例代码。

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.

我需要评论部分的逻辑,通用的逻辑会很好。谢谢。

采纳答案by Joachim Sauer

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

使用Double.valueOf()并将结果转换为long

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

回答by Bozho

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.

但这会增加开销,这对于较小的数字是不需要的。对于可在 中表示的数字long,请使用 Joachim Sauer 的解决方案。