How do I check that input is numerical?
Show older comments
I'm trying to create a program that will prompt the user for a numerical input, for example: 'What age are you?'. I know how to prompt the user to ask for an input, but I want to know how to check the answer to make sure it is a numerical figure, ie to stop the user putting in the answer 'twelve'. Any help would be greatly appreciated.
Seán
1 Comment
More reliable than str2num is to use str2double (which does not call eval and does not evaluate arbitrary code). str2double outputs NaN for invalid input strings, so simply do this:
val = str2double(input('What age are you?','s'));
if isnan(val)
... not a number
else
... was number
end
See KSSV's answer for another example of using str2double.
Accepted Answer
More Answers (1)
Thorsten
on 24 Apr 2017
Using
isnumeric
Categories
Find more on Data Type Conversion 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!