Skip to content

Instantly share code, notes, and snippets.

@oscarrenalias
Created December 15, 2011 11:12
Show Gist options
  • Save oscarrenalias/1480742 to your computer and use it in GitHub Desktop.
Save oscarrenalias/1480742 to your computer and use it in GitHub Desktop.
How to check if a string is actually a number without attempting to convert it first, in Scala
//
// Compile and run:
// scalac isnumber.scala
// scala IsNumber
//
// this is the class that provides the isNumber method when called on java.lang.String
class ExtendedString(s:String) {
def isNumber: Boolean = s.matches("[+-]?\\d+.?\\d+")
}
// and this is the companion object that provides the implicit conversion
object ExtendedString {
implicit def String2ExtendedString(s:String) = new ExtendedString(s)
}
import ExtendedString._
object IsNumber extends App {
println("Implicit 1: " + "123".isNumber)
println("Implicit 2:" + "123a".isNumber)
println("Implicit 3:" + "123.55".isNumber)
val l = List("1", "3", "awdf", "123")
println("Elements in list: " + l.forall(_.isNumber))
}
@leppaott
Copy link

According to this "2" is not a number and "2+3", "2*3" etc. are.

I used this.
def isNumeric(str:String): Boolean = str.matches("[-+]?\\d+(\\.\\d+)?")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment