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

前端 未结 8 557
鱼传尺愫
鱼传尺愫 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
    
    0 讨论(0)
  • 2020-12-24 02:44

    Unfortunately, this isn't in the standard library. Here's what I use:

    class SafeParsePrimitive(s: String) {
      private def nfe[T](t: => T) = {
        try { Some(t) }
        catch { case nfe: NumberFormatException => None }
      }
      def booleanOption = s.toLowerCase match {
        case "yes" | "true" => Some(true)
        case "no" | "false" => Some(false)
        case _ => None
      }
      def byteOption = nfe(s.toByte)
      def doubleOption = nfe(s.toDouble)
      def floatOption = nfe(s.toFloat)
      def hexOption = nfe(java.lang.Integer.valueOf(s,16))
      def hexLongOption = nfe(java.lang.Long.valueOf(s,16))
      def intOption = nfe(s.toInt)
      def longOption = nfe(s.toLong)
      def shortOption = nfe(s.toShort)
    }
    implicit def string_parses_safely(s: String) = new SafeParsePrimitive(s)
    
    0 讨论(0)
提交回复
热议问题