Reputation: 43
We could make a method:
def isNegNumber(s : String) : Boolean =
(s.head == '-') && s.substring(1).forall(_.isDigit)
Is there a cleaner way to do this?
Upvotes: 0
Views: 441
Reputation: 166
Another possible solution could be:
def isNegativeNumber(s: String) = s.toDoubleOption.exists(_ < 0)
Upvotes: 1
Reputation: 2734
You can use Try
and Option
to do this in a safer way. This will prevent an error if the string is not a number at all
import scala.util.Try
val s = "-10"
val t = Try(s.toDouble).toOption
val result = t.fold(false)(_ < 0)
Or even better, based on Luis' comment, starting Scala 2.13 (simpler and more efficient):
val t = s.toDoubleOption
val result = t.fold(false)(_ < 0)
Upvotes: 4
Reputation: 51271
Use a regex pattern.
"-10" matches "-\\d+" //true
It can easily be adjusted to account for whitespace.
"\t- 7\n" matches raw"\s*-\s*\d+\s*" //true
Upvotes: 1