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

前端 未结 8 608
鱼传尺愫
鱼传尺愫 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:44

    scala> import scala.util.Try
    import scala.util.Try
    
    scala> def parseDouble(s: String): Option[Double] = Try { s.toDouble }.toOption
    parseDouble: (s: String)Option[Double]
    
    scala> parseDouble("3.14")
    res0: Option[Double] = Some(3.14)
    
    scala> parseDouble("hello")
    res1: Option[Double] = None
    

提交回复
热议问题