Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check to see if a string is a decimal number in Scala

Tags:

scala

I'm still fairly new to Scala, and I'm discovering new and interesting ways for doing things on an almost daily basis, but they're not always sensible, and sometimes already exist within the language as a construct and I just don't know about them. So, with that preamble, I'm checking to see if a given string is comprised entirely of digits, so I'm doing:

def isAllDigits(x: String) = x.map(Character.isDigit(_)).reduce(_&&_) 

is this sensible or just needlessly silly? It there a better way? Is it better just to call x.toInt and catch the exception, or is that less idiomatic? Is there a performance benefit/drawback to either?

like image 598
PlexQ Avatar asked Mar 30 '12 06:03

PlexQ


People also ask

How do you check if a string is a number in Scala?

Using Character.isDigit method returns true if the character is a number.

How do you check if a string contains a substring in Scala?

Use the contains() Function to Find Substring in Scala Here, we used the contains() function to find the substring in a string. This function returns a Boolean value, either true or false.


1 Answers

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.

like image 163
Jesper Avatar answered Oct 06 '22 12:10

Jesper