我如何能转换一个字符串,如“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的空值

其他回答

你可以使用double . parsedouble()将String转换为double类型:

String text = "12.34"; // example String
double value = Double.parseDouble(text);

对于你的案例,它看起来像你想要:

double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());

试试这个, BigDecimal bdVal = new BigDecimal(str);

如果你想要双倍,那就试试 Double d = Double. valueof (str); System.out.println (String.format(“%。3f", new BigDecimal(d)));

double d = Double.parseDouble(aString);

这将把字符串aString转换为双d。

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