Convert String to double in Java

后端 未结 14 1723
傲寒
傲寒 2020-11-22 05:52

How can I convert a String such as \"12.34\" to a double in Java?

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:15

    Using Double.parseDouble() without surrounding try/catch block can cause potential NumberFormatException had the input double string not conforming to a valid format.

    Guava offers a utility method for this which returns null in case your String can't be parsed.

    https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)

    Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);

    In runtime, a malformed String input yields null assigned to valueDouble

提交回复
热议问题