How can I convert a String such as "12.34" to a double in Java?
-
5Those three answers basically just duplicating the top-voted answer posted a few years earlier sure do have a lot of upvotes.Bernhard Barker– Bernhard Barker2017-12-30 19:55:59 +00:00Commented Dec 30, 2017 at 19:55
-
Related: Convert Unicode Persian (Farsi) numbers in an EditText to double in AndroidBasil Bourque– Basil Bourque2025-09-13 01:47:57 +00:00Commented Sep 13 at 1:47
15 Answers
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());
8 Comments
double total = Double.parseDouble(jlbTotal.getText());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.Double instead of primitive type double use Double.valueOf(String).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
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
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
2 Comments
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
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
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
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
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.
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);
In runtime, a malformed String input yields null assigned to valueDouble
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
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
- String::toDouble does not parse non-ASCII valid digits
- Converting double to string
- Convert float to String and String to float in Java
- Convert string to float?
- Converting String to Number in Java
- Parse String into Number
- Convert string to decimal number with 2 decimal places in Java
- Convert Unicode Persian (Farsi) numbers in an EditText to double in Android
- Kotlin String toDouble() function not parsing certain values?
- Kotlin parse double from string
- Double conversion from String in Kotlin
14 Comments
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.\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.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.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?chars include about 400 digits while codePoints or \p{javaDigit} or \p{Nd} match about 700 digits.isDigit with Java digit.Character.isDigit and Character.isLetterOrDigit. Can you explain a little more?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.\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.