MATLAB Answers

How to check if a string contains only numbers?

617 views (last 30 days)
Rahul Pillai
Rahul Pillai on 14 Dec 2017
Commented: YT on 15 Dec 2017
Is there any expression for this ? For example :
-100 should return 1
a100b should return 0
0.1256 should return 1 and so on

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 14 Dec 2017
The easiest way is to check if str2double() returns nan. Otherwise you need to parse the string and there are a number of odd cases to account for in scientific notation.
Note: if you do use str2double() you should give some consideration as to what result you want for complex numbers, whether those are to be treated as numeric or as invalid because of the 'i' or 'j' present.

  4 Comments

Show 1 older comment
Walter Roberson
Walter Roberson on 14 Dec 2017
The question is whether a string contains only numbers; isnumeric checks whether the datatype of the object is numeric, which would be false for strings.
It is completely correct that str2double() returns either the value or NaN, which is why I said the easiest way is to check if str2double() returns nan.
string_contains_numeric = @(S) ~isnan(str2double(S))
This anonymous function works on character vectors, and on cell arrays of character vectors, and on string objects (including string arrays).
Stephen Cobeldick
Stephen Cobeldick on 15 Dec 2017
"why would it be easier than isnumeric()?"
Because isnumeric tests if the type is numeric. The question specifically states the input is string/char.
YT
YT on 15 Dec 2017
@replies, thanks for clarifying. Somehow I didn't read the title well enough. I'll remove my answer.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!