Scala - convert Array[String] to Array[Double]
You probably want to use map
along with toDouble
:
values.map(x => x.toDouble)
Or more concisely:
values.map(_.toDouble)
And for the fallback for non-double strings, you might consider using the Try
monad (in scala.util
):
values.map(x => Try(x.toDouble).getOrElse(1.0))
If you know what each line will look like, you could also do pattern matching:
values map { case Array(a, b, c) => Array(a.toDouble, b.toDouble, 1.0)}
Expanding on @DaunnC's comment, you can use the Try
utility to do this and pattern match on the result so you can avoid calling get
or wrapping your result in an Option
:
import scala.util.{Try, Success, Failure}def main = { val maybeDoubles = Array("5", "1.0", "8.5", "10.0", "item1", "item2") val convertDoubles = maybeDoubles.map { x => Try(x.toDouble) } val convertedArray = convertDoubles.map { _ match { case Success(res) => res case Failure(f) => 1.0 } } convertedArray}
This allows you to pattern match on the result of Try
, which is always either a Success
or Failure
, without having to call get
or otherwise wrap your results.
Here is some more information on Try courtesy of Mauricio Linhares: https://mauricio.github.io/2014/02/17/scala-either-try-and-the-m-word.html
You mean to convert all strings to double with a fallback to 1.0 for all inconvertible strings? That would be:
val x = Array( Array("1.0", "2.0", "item1"), Array("5", "8.9", "item2"))x.map( _.map { y => try { y.toDouble } catch { case _: NumberFormatException => 1.0 }})