327

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

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
TinyBelly
  • 3,337
  • 3
  • 17
  • 7
  • 4
    [Those](https://stackoverflow.com/a/29691243/1711796) [three](https://stackoverflow.com/a/22577302/1711796) [answers](https://stackoverflow.com/a/38695669/1711796) basically just duplicating the top-voted answer posted a few years earlier sure do have a lot of upvotes. – Bernhard Barker Dec 30 '17 at 19:55

14 Answers14

509

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());
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • so my coding should be double total = Double.parseDouble(string);? – TinyBelly Apr 24 '11 at 09:20
  • 4
    @TinyBelly: yeah it looks like you want: `double total = Double.parseDouble(jlbTotal.getText());` – WhiteFang34 Apr 24 '11 at 09:22
  • sry for asking.. so if i put jlbTotal = new JLabel ("The total " + total) i need to remove "The total" so i can get the value of total? i having a problem with this it "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "total Total : RM24.00"" – TinyBelly Apr 24 '11 at 09:55
  • 2
    @TinyBelly: you need to extract the part of the text from the string that you want to parse for the double. Here's one way you could do it for your case, though I can't guarantee it will work for everything: `double total = Double.parseDouble(jlbTotal.getText().replaceAll("[^0-9.]", ""));` - this basically replaces all characters that aren't a number or `.` to nothing, leaving only the number and decimal point to be parsed. – WhiteFang34 Apr 24 '11 at 10:01
  • 4
    using double for price calculations is not advisable. – Bozho Apr 24 '11 at 10:13
  • You may take a look at `DecimalFormatSymbols` to get the decimal delimiters at runtime, better than hard coding. – mike Aug 15 '13 at 09:33
  • It seems parseDouble is vulnerable. http://www.hpenterprisesecurity.com/vulncat/en/vulncat/java/denial_of_service_parse_double.html http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/ – Rami Del Toro Jun 27 '14 at 15:12
  • 4
    For those lured here while searching for result of class `Double` instead of primitive type `double` use `Double.valueOf(String)`. – Pshemo Jul 26 '18 at 17:28
56

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(",",".") );
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
TmRocha
  • 561
  • 4
  • 2
  • 2
    Another option: DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols sfs = new DecimalFormatSymbols(); sfs.setDecimalSeparator(','); df.setDecimalFormatSymbols(sfs); df.parse(number); – Robertiano Dec 11 '14 at 08:46
40

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.

Alex Oczkowski
  • 434
  • 6
  • 10
  • 2
    No, String.valueOf(something) returns a String representation of something: if something is a built-in type or if it is an Object and it is null, otherwise it is equivalent to someObject.toString(). To get a Double from a String one has to do it the other way round as shown in the other answers (Double.valueOf(someString) returns a Double, and Double.parseDouble(someString) returns a double). – jpp1 Jul 27 '15 at 17:28
37
double d = Double.parseDouble(aString);

This should convert the string aString into the double d.

Andreas Vinter-Hviid
  • 1,482
  • 1
  • 11
  • 27
31

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);
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
20

You only need to parse String values using Double

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
Harshal Patil
  • 6,659
  • 8
  • 41
  • 57
17

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();
JBWanscher
  • 340
  • 3
  • 8
8
String double_string = "100.215";
Double double = Double.parseDouble(double_string);
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
6

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.

Jiten
  • 61
  • 1
  • 1
  • 1
    You can just assign a Double to a double from Java 5 onward thanks to autoboxing / unboxing. Related: [What is difference between Double.parseDouble(string) and Double.valueOf(string)?](https://stackoverflow.com/q/10577610) – Bernhard Barker Dec 30 '17 at 20:09
4

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

faisalsash
  • 43
  • 1
  • 4
2

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

DYS
  • 2,826
  • 2
  • 23
  • 34
  • *"returns 0.0 in case your String can't be parsed"* - The Javadoc doesn't support that claim. – Tom Jan 09 '18 at 09:17
  • @Tom It returns null value Double type which can be converted to 0.0 double type – DYS 13 secs ago edit – DYS Jan 09 '18 at 09:19
  • 1
    It can, but not automatically and your snippet fails to do that. – Tom Jan 09 '18 at 09:26
2

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;
}
2
String s = "12.34";
double num = Double.valueOf(s);
-1

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