Convert String to double in Java

后端 未结 14 1659
傲寒
傲寒 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:27

    Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ; took all the cases for any string double with Eng:"Bader Qandeel"

    public static double str2doubel(String str) {
        double num = 0;
        double num2 = 0;
        int idForDot = str.indexOf('.');
        boolean isNeg = false;
        String st;
        int start = 0;
        int end = str.length();
    
        if (idForDot != -1) {
            st = str.substring(0, idForDot);
            for (int i = str.length() - 1; i >= idForDot + 1; i--) {
                num2 = (num2 + str.charAt(i) - '0') / 10;
            }
        } else {
            st = str;
        }
    
        if (st.charAt(0) == '-') {
            isNeg = true;
            start++;
        } else if (st.charAt(0) == '+') {
            start++;
        }
    
        for (int i = start; i < st.length(); i++) {
            if (st.charAt(i) == ',') {
                continue;
            }
            num *= 10;
            num += st.charAt(i) - '0';
        }
    
        num = num + num2;
        if (isNeg) {
            num = -1 * num;
        }
        return num;
    }
    

提交回复
热议问题