PDA

View Full Version : Catching improper StrToFloat values



WILL
04-11-2006, 03:31 PM
For some odd reason I cannot seem to recall a proper way to catch improper values fed to StrToFloat().

I've even used try .. except, but it doesn't seem to want to catch it. :?

Anyone know a nice way to do this?

I guess I'm used to Delphi where the TEdit components can be set to automatically block improper numerical characters. 0-9, '-' and '.'

Traveler
04-11-2006, 04:24 PM
There's possibly a function for that, until then, you could write your own.
Something like:


function checkValue(text:string):boolean;
var i : byte;
begin
result := false;
for i := 1 to length(Text) do
begin
if not (text[i] in ['0'..'9','.']) then
begin
result := true;
exit;
end;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if checkValue(edit1.text) then showmessage('incorrect value');
end;

technomage
04-11-2006, 04:24 PM
Best thing to use StrToFloatDef function (Like StrToIntDef) which catches the EConvertError and returns the default value. I checked and FreePascal has this function :D

Traveler
04-11-2006, 04:27 PM
Two posts at (almost?) the exact same time :D

WILL
04-11-2006, 04:49 PM
:shock: *whew* that was fast, thanks guys! ;)

Hmm... considered both solutions. (At least both approaches to the solution.)

Traveler, yours is a bit more involved, but I'd really only consider it unless I could not find something more elegant, like StrToFloatDef. :lol:

I'll give that a go and if I don't like whats involved then I guess I go with the brute force method approach.

Thanks again guys! ;)


BTW, am I right in assuming that this is a non-issue in Delphi's components? I remember having to deal with this before, but it was never quite so tricky to resolve.

Nitrogen
04-11-2006, 07:05 PM
Also another common thing that always happens:

If you are using a Try, Except loop in Delphi, and it still breaks on the error, just turn off Stop on Delphi Exceptions in the Debugger options page.