[英]How to convert a include “e+” string to long?
像1.3094266712875436e+18
轉換為1309426671287543600
我寫這樣的方法,有沒有更好的方法?
public static void main(String[] args) {
String a = "1.3094266712875436e+18";
System.out.println(convert(a));
}
private static long convert(String a) {
StringBuilder sb = new StringBuilder(a.length());
StringBuilder sb2 = new StringBuilder(2);
boolean isPlus = false;
boolean countLength = false;
int length = 0;
for (char c : a.toCharArray()) {
if ('.' == c) {
countLength = true;
continue;
}
if ('e' == c) {
continue;
}
if ('+' == c) {
isPlus = true;
continue;
}
if (isPlus) {
sb2.append(c);
} else {
sb.append(c);
if (countLength) {
length++;
}
}
}
System.out.println(sb.toString());
System.out.println(sb2.toString());
long pow = 1;
for (int i = 0; i < Integer.parseInt(sb2.toString()) - length; i++) {
pow = pow * 10;
}
System.out.println(pow);
return Long.parseLong(sb.toString()) * pow;
}
打印
13094266712875436
18
100
1309426671287543600
您可以使用BigDecimal
。 這將精確地解析一個十進制字符串,然后您可以使用longValue()
將其轉換為long。
String a = "1.3094266712875436e+18";
long value = new BigDecimal(a).longValue();
System.out.println(value);
輸出:
1309426671287543600
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.