How to determine if a string can be converted to a numerical value?

조회 수: 37 (최근 30일)
Liqing
Liqing 2011년 3월 23일
답변: Leon 2019년 6월 4일
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.

채택된 답변

Walter Roberson
Walter Roberson 2011년 3월 23일
Determining whether a string represents a legal numeric value is fairly messy if you wish to accept complete exponential floating point sequence and yet detect all malformed numbers. By and large it is the decimal point that causes the most problems, as it is optional but when it appears there can be numbers before it and/or numbers after it, but it is not legal for it to appear without numbers. .0e-1 is legal, 0.e-1 is legal, 0.0e-1 is legal, but .e-1 is not. The work to recognize whether a number is legal or not is very nearly the same as the work to determine the value of the number.
If you want to accept numbers but not 'nan' or one of the infinities, then you can use (e.g.)
all(ismember(potentialnumber, '0123456789+-.eEdD'))
and if it is true then try the conversion, and if the conversion fails then or the test was false, it was a string. You can improve on this test, such as by pre-checking whether the number of exponent characters is at most 1.

추가 답변 (3개)

Kaustubha Govind
Kaustubha Govind 2011년 3월 23일
[num, status] = str2num(str)
status=0 if conversion is not successful, and 1 if it is.
  댓글 수: 4
Matt Tearle
Matt Tearle 2011년 3월 23일
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
Florian Schwaiger 2015년 2월 23일
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
Alexander 2016년 2월 26일
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
Leon 2019년 6월 4일
Old thread, but the function 'isfloat" will do the trick.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by