How to check to see if a string is a decimal number in Scala
You also may consider something like this:
import scala.util.control.Exception.allCatch
def isLongNumber(s: String): Boolean = (allCatch opt s.toLong).isDefined
// or
def isDoubleNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
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.
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+"""