Convert String to double in Java

JavaStringCastingDoubleType Conversion

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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());

Solution 2 - Java

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(",",".") );

Solution 3 - Java

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.

Solution 4 - Java

double d = Double.parseDouble(aString);

This should convert the string aString into the double d.

Solution 5 - Java

Use new BigDecimal(string). This will guarantee proper calculation later.

As a rule of thumb - always use BigDecimal for sensitive calculations like money.

Example:

String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);

Solution 6 - Java

You only need to parse String values using Double

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);

Solution 7 - Java

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();

Solution 8 - Java

String double_string = "100.215";
Double double = Double.parseDouble(double_string);

Solution 9 - Java

There is another way too.

Double temp = Double.valueOf(str);
number = temp.doubleValue();

Double is a class and "temp" is a variable. "number" is the final number you are looking for.

Solution 10 - Java

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

Solution 11 - Java

String s = "12.34";
double num = Double.valueOf(s);

Solution 12 - Java

Using Double.parseDouble() without surrounding try/catch block can cause potential NumberFormatException had the input double string not conforming to a valid format.

Guava offers a utility method for this which returns null in case your String can't be parsed.

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)

Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);

In runtime, a malformed String input yields null assigned to valueDouble

Solution 13 - Java

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

Solution 14 - Java

Try this, BigDecimal bdVal = new BigDecimal(str);

If you want Double only then try Double d = Double.valueOf(str); System.out.println(String.format("%.3f", new BigDecimal(d)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTinyBellyView Question on Stackoverflow
Solution 1 - JavaWhiteFang34View Answer on Stackoverflow
Solution 2 - JavaTmRochaView Answer on Stackoverflow
Solution 3 - JavaAlex OczkowskiView Answer on Stackoverflow
Solution 4 - JavaAndreas Vinter-HviidView Answer on Stackoverflow
Solution 5 - JavaBozhoView Answer on Stackoverflow
Solution 6 - JavaHarshal PatilView Answer on Stackoverflow
Solution 7 - JavaJBWanscherView Answer on Stackoverflow
Solution 8 - JavaHabibur Rahman OvieView Answer on Stackoverflow
Solution 9 - JavaJitenView Answer on Stackoverflow
Solution 10 - JavafaisalsashView Answer on Stackoverflow
Solution 11 - JavaRanjith AlappadanView Answer on Stackoverflow
Solution 12 - JavaDYSView Answer on Stackoverflow
Solution 13 - JavaAhmed M Bader El-DinView Answer on Stackoverflow
Solution 14 - JavaPritesh LadheView Answer on Stackoverflow