#2339 Check if Str is a Number

Hertz Sat 30 Aug 2014

I can't find a way to check if a Str is a number or digit. For example, let's say I wanted to know if "23" is a number, How would I do that? Or if "abc" was a number.

SlimerDude Sat 30 Aug 2014

Strange, there is Str.isAlpha() and Str.isAlphaNum() but no Str.isNum().

So it seems there's no direct method but you could use:

"abc".all { it.isDigit }  // --> false
"123".all { it.isDigit }  // --> true

Hertz Sat 30 Aug 2014

Thanks, that solved my problem.

rasa Sun 31 Aug 2014

Yes, that might solve the problem, but it's not a general solution. Consider this:

"123".all { it.isDigit }  // --> true
"123.4".all { it.isDigit }  // --> false

This can be solved like this:

"123.4q".toDecimal(false) != null ? true : false // returns false
"123.4".toDecimal(false) != null ? true : false // returns true

or if you want return value immediately, use this:

"123.4q".toDecimal(false) ?: -1 // returns -1
"123.4".toDecimal(false) ?: -1 // returns 123.4

tomcl Sun 31 Aug 2014

That will not work for negative numbers, or numbers with a decimal point:

"abc".toDecimal(false) != null // -->true

"-22".toDecimal(false) != null // -->false

"1.12".toDecimal(false) != null // --> true

EDIT - rasa - you got there before me!

One change, I don't think you need the ternary conditional operator - != returns true or false as needed.

Tom

rasa Sun 31 Aug 2014

Yes. Ternary operator is not needed. But, you are wrong about negative numbers and numbers with decimal point. It will work for them either:

"abc".toDecimal(false) != null  // --> false
"-22".toDecimal(false) != null  // --> true
"1.12".toDecimal(false) != null // --> true

or this may be easier to read:

"abc".toDecimal(false) == null  // --> true
"-22".toDecimal(false) == null  // --> false
"1.12".toDecimal(false) == null // --> false

tomcl Mon 1 Sep 2014

Agreed - I meant the OTHER method does not work for these!

Login or Signup to reply.