Rajarshi Bhadra Rajarshi Bhadra - 7 days ago 4x
Scala Question

String to numeric conversion using regex in scala

Hi have an array of numbers as string:

val original_array = Array("-0,1234567",......)
which is a string and I want to convert to a numeric Array.

val new_array = Array("1234567", ........)

How can I aheive this in scala?

Using original_array.toDouble is giving error


The simple answer is ...

val arrNums = Array("123", "432", "99").map(_.toDouble)

... but this a little dangerous because it will throw if any of the strings are not proper numbers.

This is safer...

val arrNums = Array("123", "432", "99").collect{ case n 
    if n matches """\d+""" => n.toDouble

... but you'll want to use a regex pattern that covers all cases. This example won't recognize floating point numbers ("1.1") or negatives ("-4"). Something like """-?\d*\.?\d+""" might fit your requirements.