335

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

2

15 Answers 15

519

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());
Sign up to request clarification or add additional context in comments.

8 Comments

so my coding should be double total = Double.parseDouble(string);?
@TinyBelly: yeah it looks like you want: double total = Double.parseDouble(jlbTotal.getText());
@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.
using double for price calculations is not advisable.
For those lured here while searching for result of class Double instead of primitive type double use Double.valueOf(String).
|
57

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

1 Comment

Another option: DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols sfs = new DecimalFormatSymbols(); sfs.setDecimalSeparator(','); df.setDecimalFormatSymbols(sfs); df.parse(number);
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.

1 Comment

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).
37
double d = Double.parseDouble(aString);

This should convert the string aString into the double d.

2 Comments

aString is refer to what? can u help me explain more?
aString is just a string. More specifically the string you want to convert to a number.
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);

Comments

20

You only need to parse String values using Double

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

Comments

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

Comments

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

Comments

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.

1 Comment

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

Comments

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

3 Comments

"returns 0.0 in case your String can't be parsed" - The Javadoc doesn't support that claim.
@Tom It returns null value Double type which can be converted to 0.0 double type – DYS 13 secs ago edit
It can, but not automatically and your snippet fails to do that.
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;
}

Comments

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

Comments

1

Java Integer::parseInt and Kotlin String.toInt accept non-English digits too (like ۴).
Java new BigDecimal(String) and Kotlin String.toBigDecimal also accept non-Latin digits.

Here is a function that accepts non-ASCII digits and some more separator chars in a double:

Java

public double parseAsDouble(String string) {
    var trimmed = string.trim();
    var builder = new StringBuilder(trimmed.length());
    for (int i = 0; i < trimmed.length(); i++) {
        var character = trimmed.charAt(i);
        if (Character.isDigit(character)) {
            builder.append(Character.getNumericValue(character));
        } else if (character == '+' || character == '-') {
            builder.append(character);
        } else if (character == '٫' || character == '/' || character == '.') {
            builder.append(".");
        } else if (character != '٬' && character != ',') {
            throw new NumberFormatException("Illegal character: " + character);
        }
    }
    return Double.parseDouble(builder.toString());
}

Another solution using the int codepoints (supporting more digit characters):

public double parseAsDouble(String string) {
    var normalized = string
            .strip()
            .codePoints()
            .mapToObj(codePoint -> {
                if (Character.isDigit(codePoint)) {
                    return String.valueOf(Character.digit(codePoint, 10));
                } else if (codePoint == '+' || codePoint == '-') {
                    return Character.toString(codePoint);
                } else if (codePoint == '٫' || codePoint == '/' || codePoint == '.') {
                    return ".";
                } else if (codePoint == '٬' || codePoint == ',') {
                    return "";
                } else {
                    // To allow (ignore) illegal characters in the number string, replace below line with return "";
                    throw new NumberFormatException("Illegal character: " + Character.toString(codePoint));
                }
            })
            .collect(Collectors.joining());
    return Double.parseDouble(normalized);
}

Kotlin

fun String.parseAsDoubleOrNull(): Double? = buildString(length) {
    for (char in [email protected]()) {
        if (char.isDigit()) append(char.digitToInt())
        else if (char == '+' || char == '-') append(char)
        else if (char == '٫' || char == '/' || char == '.') append('.')
        // To throw exception for illegal chars, replace return null with error("Illegal char: $char")
        // To allow (ignore) illegal characters, comment the entire line below
        else if (char != ',' && char != '٬') return null
    }
}.toDoubleOrNull()

Another solution:

fun String.parseAsDoubleOrNull(): Double? = this
    .mapNotNull {
        when (it) {
            '٬', ',' -> null // Removes thousands separators
            '٫', '/' -> '.'  // Nomalizes decimal separators
            else -> it
        }
    }
    // To allow (ignore) illegal characters, uncomment below line
    // .filter { it.isDigit() || it == '.' || it == '-' || it == '+' }
    .map { it.digitToIntOrNull() ?: it }
    .joinToString(separator = "")
    .toDoubleOrNull()

Tests

"3۴5"          to 345.0,
"    ۳4۵  "    to 345.0,
"    +۳4۵  "   to 345.0,
"    -3۴۵  "   to -345.0,
" ۰۹۱۲3۴56۷۸۹" to 9123456789.0,
"1,234/56789"  to 1234.56789,
"۱٬۲۳۴٫۵۶۷۸۹"  to 1234.56789,
"1٬۲34.۵۶۷8۹"  to 1234.56789,
"12,3,456.123" to 123456.123,
".۱234۵"       to 0.12345,
// Some edge cases treated as valid:
"۱23۴5."       to 12345.0,
"123,.456"     to 123.456,
",123.456"     to 123.456,
"123.45,6"     to 123.456,
"1,,23.456"    to 123.456,

// Invalid strings:
"123abc" to null/exception,
"abc123" to null/exception,
"12 3"   to null/exception,
"12-3"   to null/exception,
"12+3"   to null/exception,
"--123"  to null/exception,
"123..45"to null/exception,
"-"      to null/exception,
","      to null/exception,
"."      to null/exception,
" "      to null/exception,
""       to null/exception,
null     to null/exception

Notes

  • They accept more than 700 types of digit characters
  • They accept any combination of Latin(English)/Persian(Farsi)/Arabic digits and separators
  • They accept standard Persian/Farsi and Arabic thousands separator ٬ (Shift+2)
  • They accept standard Persian/Farsi and Arabic decimal separator ٫ (Shift+3)
  • They accept the non-standard slash / and dot/period/point . as Persian decimal separators
  • You can modify the checks to add thousands and decimal seprators of your locale too

Related

14 Comments

Good idea, but you have fallen into the trap of using the essentially-broken type char. Instead use code point integer numbers to work with individual characters. I posted similar code minutes ago by coincidence, showing the use of codepoints. If convenient, please comment there if you spot any problems as I am not familiar with non-Latin numbers and scripts. And you may want to use testing source code I posted there.
I'm a little confused. I tested this code snippet to compare char and codepoint and \p{javaDigit} regex behavior. The codepoint and regex both match about 700 types of chars depending on Java version. The char matches more than 6000. When changing the regex to \p{N}, it matches about 1900 chars.
Added a new solution in the post body, hopefully addressing your comment (though I think currently both the solutions are equivalent and do the same thing)
Your linked code casts inappropriately. char is a 16-bit type. So its range runs from 0 through (2^16)-1 or 65,535, hex 0000 to FFFF. I don’t know what happens when you cast an int bigger than 65,535 to a char. Nothing good, I assume. Certainly such a cast makes no sense. As I said, avoid char, having been essentially broken since Java 2 when Unicode expanded beyond the BMP. The underlying implementation details of strings in Java (char) should never have been exposed. That exposure violated encapsulation.
I replaced charAt with codePointAt. But, did not see anywhere to recommend codePointAt over charAt. The Kotlin Int.toChar says it grabs the least significant 16 bits (right-most) bits of the int. Java seems to do the same thing. So, how else can I convert or cast an int to char?
OK. Previous code snippet was wrong and had bug. This new fixed code snippet shows that chars include about 400 digits while codePoints or \p{javaDigit} or \p{Nd} match about 700 digits.
I posted here code to see and count all 610 digit characters found in Java 12, Unicode 11.0.0.
Do not conflate isDigit with Java digit.
I don't understand. You have linked to Character.isDigit and Character.isLetterOrDigit. Can you explain a little more?
Oops. I meant isJavaLetterOrDigit. I believe the Java language specification recognizes only a subset of digit characters as digits with regard to Java naming rules. Your linked code used a regex criterion JavaDigit which I suspect does not mean the same as a Unicode digit.
IntelliJ completion says \p{javaDigit} is the same as Java Character.isDigit() (it also seems to happen to be the same as \p{Nd} regex`); all three of them matching the same set of 700 or so digit chars.
|
-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)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.