我如何能转换一个字符串,如“12.34”到双在Java?
当前回答
要将字符串转换回double类型,请尝试以下操作
String s = "10.1";
Double d = Double.parseDouble(s);
parseDouble方法将达到预期的效果,Double.valueOf()方法也是如此。
其他回答
使用新的BigDecimal(string)。这将保证以后的正确计算。
作为一个经验法则-总是使用BigDecimal敏感的计算,如金钱。
例子:
String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);
使用此转换任何字符串数字为double当你需要int时,只需将数据类型从num和num2转换为int; 把所有的情况下,任何字符串double与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;
}
再次引用上面Robertiano的引用-因为这是迄今为止最通用和本地化自适应的版本。它值得一个完整的帖子!
另一个选择:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
您只需要使用Double解析String值
String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
还有另一种方法。
Double temp = Double.valueOf(str);
number = temp.doubleValue();
Double是一个类,“temp”是一个变量。 “number”是你要找的最终数字。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- Printf与std::字符串?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作