How can I convert a String
such as \"12.34\"
to a double
in 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();
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());
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;
}
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.
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(",",".") );
String double_string = "100.215";
Double double = Double.parseDouble(double_string);