Normally I would do the following to save a string value into the database
DataModule.tbTableNumber.Value := StrToFloat(edtNumber.text);
Now the problem comes when the user enters something that cannot convert to a number. How would I be able to prevent this? Can a person use an exception and how would I write this exception?
I'm using Delphi XE2.
The best solution (IMHO) is to use TryStrToFloat
:
procedure TForm1.Button1Click(Sender: TObject);
var
myfloat: double;
begin
if TryStrToFloat(Edit1.Text, myfloat) then
DataModule.tbTableNumber.Value := myfloat
else
ShowMessage('Incorrect value.');
end;
I don't think it is particularly 'clean' to use a try..except
when when the error is as trivial and, in fact, as expected, as in this case.
You can catch the exception with the following
try
val := StrToFloat(edtNumber.text);
except
on E: EConvertError do
begin
ShowMessage( 'Entered Data is not a valid Floating Point number' );
end;
end;
You might also want to look at
StrToFloatDef( edtNumber.text, -1 )
If you just need to ensure you convert returns a valid number
There are many controls which can be told only to accept numeric input, and this has some benefits over the approach you accepted as your answer.
The jedi JVCL library for example includes several numeric input controls and the basic VCL includes a few possibilities, including the Spin Edit control which is for input of integer values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With