我如何能转换一个字符串,如“12.34”到双在Java?
当前回答
使用此转换任何字符串数字为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;
}
其他回答
使用新的BigDecimal(string)。这将保证以后的正确计算。
作为一个经验法则-总是使用BigDecimal敏感的计算,如金钱。
例子:
String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);
再次引用上面Robertiano的引用-因为这是迄今为止最通用和本地化自适应的版本。它值得一个完整的帖子!
另一个选择:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
double d = Double.parseDouble(aString);
这将把字符串aString转换为双d。
使用double . parsedouble()而没有周围的try/catch块可能会导致潜在的NumberFormatException,输入的双字符串不符合有效的格式。
Guava为此提供了一个实用程序方法,如果你的字符串无法解析,该方法将返回null。
https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html tryParse(以)
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);
在运行时,格式错误的String输入会产生赋值给valueDouble的空值
这就是我要做的
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 " the 输出将双数字45563.0
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 如何删除表中特定列的第一个字符?