0 Downloads
Updated 22 Nov 2004
No License
STRINGISNUMBER returns 1 if the input string contains only a number and otherwise a zero
Created as an example for the thread "How to determine if an inputfield contains chars or numbers ?"
USAGE:
>> StringIsNumber('aseea')
ans = 0
>> StringIsNumber('333')
ans = 1
>> StringIsNumber('333.123')
ans = 1
>> StringIsNumber('.123')
ans = 1
>> StringIsNumber('0.123')
ans = 1
>> StringIsNumber('0.123a')
ans = 0
IT'S NOT FANCY BUT IT WORKS
Michael Robbins (2021). StringIsNumber (https://www.mathworks.com/matlabcentral/fileexchange/6283-stringisnumber), MATLAB Central File Exchange. Retrieved .
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Create scripts with code, output, and formatted text in a single executable document.
Simpler and faster,would be to use the inbuilt STR2DOUBLE:
>> ~isnan(str2double('aseea'))
ans = 0
>> ~isnan(str2double('333'))
ans = 1
>> ~isnan(str2double('333.123'))
ans = 1
>> ~isnan(str2double('.123'))
ans = 1
>> ~isnan(str2double('0.123'))
ans = 1
>> ~isnan(str2double('0.123a'))
ans = 0
Another idea:
[x, count, err, next] = sscanf(Str, '%g', 1);
isNumber = (count == 1) && (next == numel(Str) + 1);
Simple robust function. Does not recognize negetive numbers and scientific notation. Nice alternative to ~isempty(str2num(str)) approach which sametimes gives strange results (try str = 'sphere' ).