So, apparently, Java's java.lang.Double#parseDouble is able to parse all kinds of strings, e.g. NaN, Infinity and other.
The answer to your problem seems to be BigDecimal(myString).toDouble
Out of curiosity, here is, what three different approaches return for various kinds of input strings:
def main(args: Array[String]): Unit = {
val strings = Seq("Infinity", "NaN", "9.0d", "9d", "9f", "9.0", "9.1", "1.4e14")
val parsers = Seq(
("Double", (s: String) => s.toDouble),
("BigDecimal", (s: String) => BigDecimal(s).toDouble),
("NumberFormat", (s: String) => NumberFormat.getNumberInstance.parse(s).doubleValue()),
)
for (string <- strings) {
println(s"\n------------- $string ------------")
for ((name, parser) <- parsers) {
val result = Try(parser(string)) match {
case scala.util.Success(value) => value
case scala.util.Failure(ex) => ex.toString
}
println(name.reverse.padTo(20, " ").reverse.mkString + " -> " + result)
}
}
}
Result:
------------- Infinity ------------
Double -> Infinity
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> java.text.ParseException: Unparseable number: "Infinity"
------------- NaN ------------
Double -> NaN
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> java.text.ParseException: Unparseable number: "NaN"
------------- 9.0d ------------
Double -> 9.0
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> 9.0
------------- 9d ------------
Double -> 9.0
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> 9.0
------------- 9f ------------
Double -> 9.0
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> 9.0
------------- 9.0 ------------
Double -> 9.0
BigDecimal -> 9.0
NumberFormat -> 9.0
------------- 9.1 ------------
Double -> 9.1
BigDecimal -> 9.1
NumberFormat -> 9.1
------------- 1.4e14 ------------
Double -> 1.4E14
BigDecimal -> 1.4E14
NumberFormat -> 1.4
BigDecimal(myString).toDouble