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?
Asked
Active
Viewed 1.5k times
7
-
Please clarify whether you want to convert to `Int` or `Double`, or rather need to check if a `String` can be converted to a type that has an implicit `Numeric[_]` – Sascha Kolberg Aug 13 '15 at 11:05
-
Just suppose my input is coming as "111" so its numeric to i raise a flag saying its numeric, or same in case if input comes like "-78" but if my input comes like "111.67" I need to raise flag as decimal. – yash Aug 14 '15 at 08:43
3 Answers
13
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

elm
- 20,117
- 14
- 67
- 113
-
3try catch for such check is a waste of resources, you can check the string directly – Victor P. Jun 17 '16 at 08:34
0
Assuming you want not only to convert by using Try(x.toInt)
or Try(x.toFloat)
but actually want a validator that takes a String
and return true
iff the passed String
can be converted to a A
with implicit evidence: Numeric[A]
.
Then I would say: Afaik, no it is not possible. Especially, since Numeric
is not sealed. That is you can create your own implementations of Numeric
Primitive types like Int, Long, Float, Double
can be easily extracted with a regular expression.

Sascha Kolberg
- 7,092
- 1
- 31
- 37
0
I tried this and its working fine:
val s = "-1112.12" s.isNumeric && (s.contains('.')==false)

yash
- 129
- 1
- 2
- 6