简体   繁体   English

将字符串转换为双精度时,删除 java 中第一个后的任何多个点或任何小数点

[英]Remove any multiple points or any decimal points after the first one in java when converting string to double

I am having a string which may have a value like 1000.021 which i then convert to double using the method below我有一个字符串,它的值可能类似于 1000.021,然后我使用下面的方法将其转换为 double

double amount = Double.parseDouble(1000.021);

This just works fine when its a single decimal place but when i get a sting value like 1000.021.2344.455 it crashes on parsing the double from String to double how can i be able to remove the extra decimal places after the first one so the i have a double like 1000.0212344455 when i get a value like 1000.021.2344.455当它只有一个小数位时,这很好用,但是当我得到一个像 1000.021.2344.455 这样的刺值时,它在将双精度从字符串解析为双精度时崩溃我如何能够删除第一个小数位之后的额外小数位,所以我有当我得到像 1000.021.2344.455 这样的值时,像 1000.0212344455 这样的双倍

Below is what i have tried but it just removes all the decimal places and it just accepts a number with a single decimal place in the.format以下是我尝试过的,但它只是删除了所有小数位,它只接受.format 中有一个小数位的数字


new DecimalFormat("#").format(100.22);

I just tried that one:我刚试过那个:

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 Output:1000.0212344455

Try the below code for the conversion:尝试以下代码进行转换:

    public static double toDouble(String s) {
        int i1 = s.indexOf(".");
        return Double.parseDouble(s.substring(0, i1 + 1) + s.substring(i1).replaceAll("\\.", ""));
    }

Test case:测试用例:

@Test
public void test(){
    double v = toDouble("1000.021.2344.455");
    assert v == 1000.0212344455;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM