How to find if a Scala String is parseable as a Double or not?

前端 未结 8 600
鱼传尺愫
鱼传尺愫 2020-12-24 01:49

Suppose that I have a string in scala and I want to try to parse a double out of it.

I know that, I can just call toDouble and then catch the java num

8条回答
  •  情话喂你
    2020-12-24 02:23

    Scala 2.13 introduced String::toDoubleOption:

    "5.7".toDoubleOption                // Option[Double] = Some(5.7)
    "abc".toDoubleOption                // Option[Double] = None
    "abc".toDoubleOption.getOrElse(-1d) // Double = -1.0
    

提交回复
热议问题