Search code examples
javadouble

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

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

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


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


Solution

  • 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;
    }