Created
December 15, 2011 11:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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+)?")