Info

This question is closed. Reopen it to edit or answer.

ANSWER: How to check if you wrote string or number

1 view (last 30 days)
Hi there, this might help you out. I made a short code that takes in a number (or string) from a user and returns the number if it sure is a number or 0 if it's a string.
copy and paste in a "script" to try out. Save the script and then test it in comand window.
number = input('Type a number please = ', 's');
% this pice of code can take in both numbers or strings:
number = str2num(number);
%If the string "number" does not represent a valid number or matrix,
str2num(number) returns the empty matrix.
if isempty(number)
answer = 0;
else
answer = daysInMonth(number);
end
disp(answer)
or:
number = input('Type a number please = ', 's');
number = str2num(number);
if isempty(number)
disp('You wrote a text')
else
fprintf(' You wrote the number %2.0f\n ', number)
end
I know this might be a problem for lots of people which they need an answer to. Lets hope it helps
BenDyAsk
  5 Comments
Stephen23
Stephen23 on 22 Sep 2016
Edited: Stephen23 on 22 Sep 2016
Running str2num does not do what the OP thinks, and actually executes the input string. It does not test for string vs. number:
>> str2num('i')
ans = 0 + 1i
>> str2num('exp(3)')
ans = 20.086
>> str2num('mean(+''cheese'')')
ans = 103.50
A much better choice would be str2double.
I am going to close this question because it is misleading, and gives wrong information.

Answers (0)

Community Treasure Hunt

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

Start Hunting!