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

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

    Scalaz provides an extension method parseDouble on Strings, which gives a value of type Validation[NumberFormatException, Double].

    scala> "34.5".parseDouble
    res34: scalaz.Validation[NumberFormatException,Double] = Success(34.5)
    
    scala> "34.bad".parseDouble
    res35: scalaz.Validation[NumberFormatException,Double] = Failure(java.lang.NumberFormatException: For input string: "34.bad")
    

    You can convert it to Option if so required.

    scala> "34.bad".parseDouble.toOption
    res36: Option[Double] = None
    

提交回复
热议问题