我如何能转换一个字符串,如“12.34”到双在Java?
当前回答
使用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的空值
其他回答
使用新的BigDecimal(string)。这将保证以后的正确计算。
作为一个经验法则-总是使用BigDecimal敏感的计算,如金钱。
例子:
String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);
这就是我要做的
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
String s = "12.34";
double num = Double.valueOf(s);
再次引用上面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。
推荐文章
- 在流中使用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时停止工作