cool breeze cool breeze - 1 year ago 68
Scala Question

How to compare to strings after converting them to a double?

I'm looking for a idiomatic way of converting 2 strings to a double and then comparing them?

To safely convert to double I have:

def toDouble(s: String): Option[Double] = {
try { s.toDouble } catch { case _ => None }

So I am doing a for expression in order to compare the 2 doubles:

for {
d1 <- toDouble(s1)
d2 <- toDouble(s2)
} yield (d1 > d2)

Now say I wanted to do
(d1 < d2)
, could I somehow generalize this?

Any improvements to make this cleaner?

Answer Source
import scala.util.Try

     def f(x: String, 
           y: String, 
           compare: (Double, Double) => Boolean): Option[Boolean] = for {
         a <- Try { x.toDouble }.toOption
         b <- Try { y.toDouble }.toOption
     } yield compare(a, b)

scala> f("42", "66", _ < _)
res0: Option[Boolean] = Some(true)

scala> f("42", "66", _ > _)
res1: Option[Boolean] = Some(false)

I'd prefer a better type than Boolean, so there's room for improvement on my answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download