Convert String to double in Java

后端 未结 14 1716
傲寒
傲寒 2020-11-22 05:52

How can I convert a String such as \"12.34\" to a double in Java?

14条回答
  •  借酒劲吻你
    2020-11-22 06:17

    This is what I would do

        public static double convertToDouble(String temp){
           String a = temp;
           //replace all commas if present with no comma
           String s = a.replaceAll(",","").trim(); 
          // if there are any empty spaces also take it out.          
          String f = s.replaceAll(" ", ""); 
          //now convert the string to double
          double result = Double.parseDouble(f); 
        return result; // return the result
    }
    

    For example you input the String "4 55,63. 0 " the output will the double number 45563.0

提交回复
热议问题