Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate a Numeric character in scala? [duplicate]

Tags:

scala

my application takes in a string like this (-110,23,-111.9543633) I need to validate/retrieve inside scala script that the string whether it is Numeric or not?

like image 361
yash Avatar asked Aug 13 '15 08:08

yash


1 Answers

Consider scala.util.Try for catching possible exceptions in converting a string onto a numerical value, as follows,

Try("123".toDouble).isSuccess
Boolean = true

Try("a123".toDouble).isSuccess
Boolean = false

As of ease of use, consider this implicit,

implicit class OpsNum(val str: String) extends AnyVal {
  def isNumeric() = scala.util.Try(str.toDouble).isSuccess
}

Hence

"-123.7".isNumeric
Boolean = true

"-123e7".isNumeric
Boolean = true

"--123e7".isNumeric
Boolean = false
like image 79
elm Avatar answered Sep 18 '22 03:09

elm