How to check a numeric character in scala?

my application accepts a line like this (-110,23, -111.9543633) I need to check / get inside the scala script so that the line is numeric or not?

+5
source share
3 answers

I tried this and worked great:

val s = "-1112.12" s.isNumeric && (S.contains ('') == false)

0
source

Consider scala.util.Try to detect possible exceptions when converting a string to a numeric value as follows:

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

As ease of use, consider this implicit,

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

Consequently

 "-123.7".isNumeric Boolean = true "-123e7".isNumeric Boolean = true "--123e7".isNumeric Boolean = false 
+9
source

Assuming that you want to not only convert using Try(x.toInt) or Try(x.toFloat) , but you really want the validator to accept String and return true if the passed String can be converted to A with implicit evidence: Numeric[A] .

Then I would say: Afaik, no , this is impossible. Moreover, Numeric not sealed. That is, you can create your own Numeric implementations

Primitive types, such as Int, Long, Float, Double , can be easily extracted using regular expressions.

0
source

All Articles