我如何能转换一个字符串,如“12.34”到双在Java?


当前回答

这就是我要做的

    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 double_string = "100.215";
Double double = Double.parseDouble(double_string);

使用新的BigDecimal(string)。这将保证以后的正确计算。

作为一个经验法则-总是使用BigDecimal敏感的计算,如金钱。

例子:

String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);

如果在将字符串解析为十进制值时遇到问题,则需要将数字中的“,”替换为“”。


String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );

要将字符串转换回double类型,请尝试以下操作

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();