Testing if a input is a numerical (double) of character

조회 수: 22 (최근 30일)
Jucimar Carpe
Jucimar Carpe 2019년 8월 18일
댓글: Jucimar Carpe 2019년 8월 18일
Hi folks, i'm implementing a software on appDesigner and i want to prevent wrong entries from users.
I've tried to use the folowing code but it's not working. My gol would be, check if the user entered with a number or character. If it's a number then OK, otherwise open a warning dialog box informing the error and then stop the program.
The way i've writed it's not working.
Sbase_gerador = str2double(strrep((app.potencia.Value),',','.'));% Read entry data and convert comma to '.' if needed
teste_potencia = isnumeric(Sbase_gerador)
if teste_potencia==0
opts= struct('WindowStyle','modal','Interpreter','tex');
tensao_incorreta_t2 = warndlg('\fontsize{11}Caracteres diferentes de números não são aceitos.',...
'Entrada incorreta de dados', opts);
app.potencia.Value='0';
end

채택된 답변

Adam Danz
Adam Danz 2019년 8월 18일
편집: Adam Danz 2019년 8월 18일
You can use str2double() to convert the string to numeric. If the string did not contain something that can be converted to numeric, it will return NaN.
isNumber = ~isnan(str2double(str));
Examples
isNumber = ~isnan(str2double('100')) % true
isNumber = ~isnan(str2double(' 100 ')) % true
isNumber = ~isnan(str2double('3.1415926')) % true
isNumber = ~isnan(str2double('8.3205e+24')) % true
isNumber = ~isnan(str2double('Abcd')) % false
isNumber = ~isnan(str2double('5 and 7')) % false
  댓글 수: 6
Adam Danz
Adam Danz 2019년 8월 18일
Do you mean a certain input is not producing the expected output with the code from my answer? Or is there a different problem?
Jucimar Carpe
Jucimar Carpe 2019년 8월 18일
I let in this way.
It seems the instruction ~isnan let the variable Sbase_gerador with some random number (that i dont know what it is) because of the logical answer. And this make my calculations crazy.
Sbase_gerador = ~isnan(str2double(strrep((app.potencia.Value),',','.')))
if ~Sbase_gerador
opts= struct('WindowStyle','modal','Interpreter','tex');
potencia_incorreta = warndlg('\fontsize{11}Caracteres diferentes de números não são aceitos.',...
'Entrada incorreta de dados', opts);
app.potencia.Value='0';
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by