How to check to see if a string is a decimal number in Scala
Solution 1:
Try this:
def isAllDigits(x: String) = x forall Character.isDigit
forall
takes a function (in this case Character.isDigit
) that takes an argument that is of the type of the elements of the collection and returns a Boolean
; it returns true
if the function returns true
for all elements in the collection, and false
otherwise.
Solution 2:
Do you want to know if the string is an integer? Then .toInt
it and catch the exception. Do you instead want to know if the string is all digits? Then ask one of:
s.forall(_.isDigit)
s matches """\d+"""