[英]Remove any multiple points or any decimal points after the first one in java when converting string to double
我有一個字符串,它的值可能類似於 1000.021,然后我使用下面的方法將其轉換為 double
double amount = Double.parseDouble(1000.021);
當它只有一個小數位時,這很好用,但是當我得到一個像 1000.021.2344.455 這樣的刺值時,它在將雙精度從字符串解析為雙精度時崩潰我如何能夠刪除第一個小數位之后的額外小數位,所以我有當我得到像 1000.021.2344.455 這樣的值時,像 1000.0212344455 這樣的雙倍
以下是我嘗試過的,但它只是刪除了所有小數位,它只接受.format 中有一個小數位的數字
new DecimalFormat("#").format(100.22);
我剛試過那個:
String str = "1000.021.2344.455";
String newStr = "";
boolean dot = true;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '.' && dot) {
newStr +=str.charAt(i);
dot =false;
}
if(str.charAt(i) != '.' || dot){
newStr +=str.charAt(i);
}
}
Double num = Double.parseDouble(newStr);
System.out.println(num);
Output:1000.0212344455
嘗試以下代碼進行轉換:
public static double toDouble(String s) {
int i1 = s.indexOf(".");
return Double.parseDouble(s.substring(0, i1 + 1) + s.substring(i1).replaceAll("\\.", ""));
}
測試用例:
@Test
public void test(){
double v = toDouble("1000.021.2344.455");
assert v == 1000.0212344455;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.