4

so basically I have some input possibilities for the user where should only numbers be accepted, otherwise the user will be alerted his input was incorrect.

the input is considered a String when I read it out using a callback. now I want to check whether the string(which SHOULD contain numbers) actually DOES ONLY contain numbers, but I didnt find a solution implemented already. i tried

theString isInteger 

-is never true for the string

theString asNumber 

- ignores letters, but I want to have a clear output wether letters are included in the string or not

theString isNumber

- always false

4 Answers 4

10

In Squeak and Pharo, you have the message #isAllDigits that does exactly what you want:

'1233248539487523' isAllDigits "--> true"
1
  • 1
    #isAllDigits is probably even faster than using regex because there are only a few message sends involved, some of which can be inlined by the compiler. The regex on the other hand needs to be initialized first and the regex checks then run through a lot of code.
    – Max Leske
    Commented Sep 19, 2014 at 13:53
4

You can use a regular expression to check that the string contains only numbers:

theString matchesRegex: '\d+'

or a more complex regular expression to also allow an optional sign and decimal point:

theString matchesRegex: '-?\\d+(\\.\\d+)?'
1

Unfortunately, I could not locate messages 'isAllDigits' or 'matchesRegex'on Cincom Smalltalk. However, what you could do is extract a word from the string and convert it to a number using asNumber. So, if the returned value is 0(zero) it means that either the number is actually a 0(which could e checked with an additional condition) or string did not contain a digit/number.

1

This should work with many Smalltalks dialects:

(aString detect: [:c| c isDigit not ]) isNil ifTrue: [ "it's a number" ]. 

Not the answer you're looking for? Browse other questions tagged or ask your own question.