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

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

    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)
    

提交回复
热议问题