如何在Java中把一个字符串'如
"12.34"转换为
双数'?
你可以使用Double.parseDouble()
将 "String "转换为 "double"。
String text = "12.34"; // example String
double value = Double.parseDouble(text);
对于你的情况,看起来你想。
double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());
要将一个字符串转换回双数,请尝试以下方法
String s = "10.1";
Double d = Double.parseDouble(s);
parseDouble方法可以达到预期的效果,Double.valueOf()方法也可以。
再次引用上面Robertiano的一句话--因为这是迄今为止用途最广、本地化适应性最强的版本。 它值得写一篇完整的文章
另一个选择。
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
String double_string = "100.215";
Double double = Double.parseDouble(double_string);
这是我要做的
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
}
例如你输入字符串"4 55,63。 0 " 的 输出将双数45563.
使用Double.parseDouble()
而不使用周围的try/catch
块会导致潜在的NumberFormatException
,因为输入的双字符串不符合有效的格式。
Guava提供了一个实用的方法,在你的String不能被解析的情况下返回 "null"。
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString)。
在运行时,错误的字符串输入会产生null
分配给valueDouble
。
用这个来转换任何字符串数字为双数,当你需要int时,只需转换数据类型从num和num2到int。 用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;
}