How to check if a string contains only numbers?

Is there any expression for this ? For example :
-100 should return 1
a100b should return 0
0.1256 should return 1 and so on

 Accepted Answer

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.

7 Comments

I'm curious myself why is the 'easiest way' str2double()? In this example, why would it be easier than isnumeric()? Besides str2double() returns either the value or NaN, which is not exactly what the OP asked for.
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).
"why would it be easier than isnumeric()?"
Because isnumeric tests if the type is numeric. The question specifically states the input is string/char.
@replies, thanks for clarifying. Somehow I didn't read the title well enough. I'll remove my answer.
... but we must remember we can only check for nan by using isnan(str2double()). I just spent a long time trying to figure out why if str2double() == nan, and isequal(str2double(),nan) didn't work.
Hah, yes,
nan == nan
ans = logical
0
nan >= nan
ans = logical
0
nan < nan
ans = logical
0
all returning false is an oddity of floating point numbers. Oddly enough,
nan ~= nan
ans = logical
1
returns true, so an alternate way to test for nan is
x ~= x
I would not describe the behavior of the relational operators with one of the inputs being NaN an "oddity". It's how NaN is defined to work in the IEEE 754 specification, as summarized on the NaN Wikipedia page. In IEEE 754-2019 it's section 5.11. A short excerpt:
"Four mutually exclusive relations are possible: less than, equal, greater than, and unordered; unordered arises when at least one operand is a NaN. Every NaN shall compare unordered with everything, including itself."
If you want to tell if something is a NaN and don't want to use isnan or ismissing for whatever reason, you could use isequaln instead of isequal. isequaln explicitly treats NaN as equal to NaN.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!