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


当前回答

还有另一种方法。

Double temp = Double.valueOf(str);
number = temp.doubleValue();

Double是一个类,“temp”是一个变量。 “number”是你要找的最终数字。

其他回答

String s = "12.34";
double num = Double.valueOf(s);

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


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

您只需要使用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”是你要找的最终数字。

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

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

例子:

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