How do I ensure the user enters a numerical value
2 views (last 30 days)
Show older comments
How can I ensure that the user inputs a numerical value or a number within a range of values while using my program? I'm trying to avoid users entering letters or anything irrelevant
0 Comments
Answers (2)
Walter Roberson
on 2 Jan 2016
Read the number as a string and then check to see if the text matches a valid pattern for being numeric before accepting it. You can use regexp for this purpose, but see http://www.mathworks.com/matlabcentral/answers/260044-extracting-number-with-exponential-from-cell-array#answer_203054
Often easier is to read the number as a string and then use str2double() as that will return NaN for anything that is not a valid number; use isnan() to detect that and complain instead of using the value. str2double() will not trigger any kind of error message for strings that are not numbers.
0 Comments
Image Analyst
on 2 Jan 2016
See this snippet:
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check for a valid number.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end
% Do the same for usersValue2
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!