How to accept only positive numbers on textbox ?

Hello;
I need to put only positive number in textbox. It's a equation and about time so it's cant be negative. Which codes help me ?
S = str2num(char(get(handles.edit1 , 'String')));
if (isempty(S))
set(hObject,'String','0');
warndlg('Insert positive value','!! Warning !!');
end
I tried someting, If I put letters in textbox that give me a warning (working) but I need to change that with positive numbers.

 Accepted Answer

S = abs(S);

3 Comments

I need this code give me warning with warndlg if I input negative value.
if S < 0
warndlg('Value was negative, you shouldn't do that!');
S = -S;
end
It's working Thank you :)

Sign in to comment.

More Answers (1)

It's best to use a while loop after every imput. This is my code to force the user only imput possitive spring stiffness values. I also added a warning message box.
promt='front spring stiffness(N/mm)';
F_Kspring=input(promt);
if F_Kspring<=0 %warning message box
f = warndlg('Insert only POSITIVE values');
end
while F_Kspring<=0 %While loop for making user insert only possitive values
promt='front spring stiffness(N/mm)';
F_Kspring=input(promt);
end

2 Comments

I would avoid having the same code twice:
promt='front spring stiffness(N/mm)';
while true %While loop for making user insert only possitive values
F_Kspring=input(promt);
if F_Kspring<=0 %warning message box
f = warndlg('Insert only POSITIVE values');
else
break
end
end
Yes, this is better, then my original. Neater and the warning box appears every time when negative value is inserted.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!