Home > database >  Cleanest way to check if a string value is a negative number?
Cleanest way to check if a string value is a negative number?

Time:10-08

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?

CodePudding user response:

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)

CodePudding user response:

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
  • Related