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

36 ビュー (過去 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 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