Convert String to double in Java

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

    Citing the quote from Robertiano above again - because this is by far the most versatile and localization adaptive version. It deserves a full post!

    Another option:

    DecimalFormat df = new DecimalFormat(); 
    DecimalFormatSymbols sfs = new DecimalFormatSymbols();
    sfs.setDecimalSeparator(','); 
    df.setDecimalFormatSymbols(sfs);
    double d = df.parse(number).doubleValue();
    
    0 讨论(0)
  • 2020-11-22 06:27

    You can use Double.parseDouble() to convert a String to a double:

    String text = "12.34"; // example String
    double value = Double.parseDouble(text);
    

    For your case it looks like you want:

    double total = Double.parseDouble(jlbTotal.getText());
    double price = Double.parseDouble(jlbPrice.getText());
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-22 06:29

    To convert a string back into a double, try the following

    String s = "10.1";
    Double d = Double.parseDouble(s);
    

    The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.

    0 讨论(0)
  • 2020-11-22 06:30

    If you have problems in parsing string to decimal values, you need to replace "," in the number to "."


    String number = "123,321";
    double value = Double.parseDouble( number.replace(",",".") );
    
    0 讨论(0)
  • 2020-11-22 06:38
    String double_string = "100.215";
    Double double = Double.parseDouble(double_string);
    
    0 讨论(0)
提交回复
热议问题