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 format exception if this fails, but is there a cleaner way to do this? For example if there was a parseDouble
function that returned Option[Double]
this would qualify.
I don't want to put this in my own code if it already exists in the standard library and I am just looking for it in the wrong place.
Thanks for any help you can provide.
To check if the string contains numbers only, in the try block, we use Double 's parseDouble() method to convert the string to a Double . If it throws an error (i.e. NumberFormatException error), it means the string isn't a number and numeric is set to false . Else, it's a number.
In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java. lang. String class.
Double parseDouble() method in Java with examples The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double. Syntax: public static double parseDouble(String s)
Using the parseDouble() method Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.
For Scala 2.13+ see Xavier's answer below. Apparently there's a toDoubleOption
method now.
For older versions:
def parseDouble(s: String) = try { Some(s.toDouble) } catch { case _ => None }
Fancy version (edit: don't do this except for amusement value; I was a callow youth years ago when I used to write such monstrosities):
case class ParseOp[T](op: String => T) implicit val popDouble = ParseOp[Double](_.toDouble) implicit val popInt = ParseOp[Int](_.toInt) // etc. def parse[T: ParseOp](s: String) = try { Some(implicitly[ParseOp[T]].op(s)) } catch {case _ => None} scala> parse[Double]("1.23") res13: Option[Double] = Some(1.23) scala> parse[Int]("1.23") res14: Option[Int] = None scala> parse[Int]("1") res15: Option[Int] = Some(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With