How do I check that input is numerical?

116 ビュー (過去 30 日間)
Seán Ó Héir
Seán Ó Héir 2017 年 4 月 24 日
編集済み: Stephen23 2023 年 4 月 23 日
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 件のコメント
Stephen23
Stephen23 2017 年 4 月 24 日
編集済み: Stephen23 2017 年 4 月 24 日
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.

サインインしてコメントする。

採用された回答

Adam
Adam 2017 年 4 月 24 日
編集済み: Adam 2017 年 4 月 24 日
str2num( inputVal )
will return the number if it is valid or empty otherwise so a
if ~isempty( str2num( inputVal ) )
test would check it is a number, or remove the ~ if you want to check for not a number and give an error message in that case.
  4 件のコメント
Peter
Peter 2023 年 4 月 22 日
I'm a new user, with some help from other answers I found this solution. Option to use existing data from a file or new input; plus checking numeric input, maybe not the best solution, it works
str2num will create error message after input either i or j, compex number
doRun=true;
while doRun=true
disp('input calc_data D1:')
disp('Choose 1 or 2');
disp('1= keep old data');
disp('2= new data');
Sip_choose=input ('Choose 1 or 2: ','s');
option=str2double(Sip_choose);
if(option==1)
calc_data_D1= D1
% old value in mat file saved
break
elseif(option==2)
while doRun
D1=input('=> input calc_data D1= ','s');
D1t=str2double(D1);
TF=isstrprop(D1t,'digit');
if TF==0
D1=D1t;
% new value of D1
doRun=false;
else
disp('no numeric input')
end
end
else
disp('wrong choose of option')
disp('1 or 2 accepted only')
end
end
Stephen23
Stephen23 2023 年 4 月 23 日
編集済み: Stephen23 2023 年 4 月 23 日
"so a if ~isempty( str2num( inputVal ) ) test would check it is a number"
Note that STR2NUM is fundamentally buggy:
str = 'struct("x",pi)';
if ~isempty( str2num(str) )
disp('Oh no!')
end
Oh no!
Read the STR2NUM file to understand why. The reliable approach is to use STR2DOUBLE or SSCANF or the like.
@Peter: you can simplify your code by avoiding the conversion to numeric and using STRCMPI.

サインインしてコメントする。

その他の回答 (1 件)

Thorsten
Thorsten 2017 年 4 月 24 日
Using
isnumeric

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by