How to determine if a string can be converted to a numerical value?
Show older comments
For example, I have two strings, 'abc' and '123'. I want to process them differently. If it is '123', I would use str2num to convert it to a number for my operation. If it is 'abc', I would do some other operation. My question is how to write the sentence to detect which of them can be converted to a numerical value?
Thank you.
Accepted Answer
More Answers (3)
Kaustubha Govind
on 23 Mar 2011
[num, status] = str2num(str)
status=0 if conversion is not successful, and 1 if it is.
4 Comments
Matt Tearle
on 23 Mar 2011
Beat me to it. If status = 0, do your other operation on str.
Liqing
on 23 Mar 2011
Matt Tearle
on 23 Mar 2011
If you have a set of values you consider "missing", you don't have many options but to determine those by brute-force. But you might as well still do the conversion then test the result. Eg
num = str2num(str)
if (isempty(num) | ~isfinite(num) | (num==-999))
% not a valid number, do alternate thing
else
% number, go ahead
end
Florian Schwaiger
on 23 Feb 2015
Old thread but: you need to know that str2num uses eval internally. The following also passes this test:
>> [a, b] = str2num('SomeClassName')
a =
1x1 SomeClassName
b =
1
Alexander
on 26 Feb 2016
The following code will give you the output of str2double with an element-wise status output like str2num:
function [X,status] = MYstr2double(str)
X = str2double(str);
status = ~xor(strcmpi(strtrim(str),'NaN'),isnan(X));
end
This code works with in input that is a string or cell array of strings
Leon
on 4 Jun 2019
0 votes
Old thread, but the function 'isfloat" will do the trick.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!