How to convert Any number to Double?

Once you lost your type information at compile time, as it happens to be in your case since your input type is Any as part of its requirements, there is no more options than inspecting expectedNumber at run time with isInstanceOf.

That is masked by the implementation of type pattern matching you are doing in your proposed solution. And I think that is the best solution in your case.

However, there is an alternative which is using Try over and transforming it into an Option. e.g:

Try(expectedNumber.toString.toDouble).toOption

That's a dirty solution in so many ways (not efficient at all, using exceptions to control flow, ...) that I would definetively use your first approach


It is certainly possible, as indicated in this answer:

Use java.lang.Number to match with your case type.

def extractDouble(x: Any): Option[Double] = x match {
  case n: java.lang.Number => Some(n.doubleValue())
  case _ => None
}

Note that this also works for instances of BigDecimal and BigInteger, be it scala.math.BigDecimal or java.math.BigDecimal.


I was using the OP's solution for a while. But upon encountering some slightly corrupted data input, I subsequently changed to a combination of OP's solution and the Try solution.

  def extractDouble(expectedNumber: Any): Option[Double] = expectedNumber match {
    case i: Int => Some(i.toDouble)
    case l: Long => Some(l.toDouble)
    case d: Double => Some(d)
    case s: String => Try(s.trim.toDouble).toOption
    case _ => None
  } 

the case s:String line may save you a bit of debugging and head scratching down the line if you are dealing with big and potentially messy data