Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Any number to Double?

I need to do some raw data parsing and I am forced to work with Any type.

If the data I read is in any numeric format (Int/Double/Long/...) I need to convert it to Double, otherwise (eg. String) I need to leave it empty.

This is what I came up with:

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 _ => None
}

This obviously doesn't look even decently. Is there any better way to deal with this in Scala?

like image 996
TheMP Avatar asked Feb 24 '17 07:02

TheMP


2 Answers

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

like image 112
Pablo Francisco Pérez Hidalgo Avatar answered Sep 28 '22 03:09

Pablo Francisco Pérez Hidalgo


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.

like image 39
Adowrath Avatar answered Sep 28 '22 05:09

Adowrath