Code of the Day:
Code of the Day:
try
if trim(Value) <> '' then
Value2 := inttostr(strtoint(Value))
else
Value2 := trim(Value);
except
ShowMessageAPP('"' + Value + '" is not a number');
end;
try
if trim(Value) <> '' then
Value2 := inttostr(strtoint(Value))
else
Value2 := trim(Value);
except
ShowMessageAPP('"' + Value + '" is not a number');
end;
Are you sure this is actual code and not a Zen session? :-)
ReplyDeleteActual code. :-(
ReplyDeleteThat's nice - put it on docwiki! :p
ReplyDeleteIs there a prize? I could offer up some real stunners. ;)
ReplyDeleteI like to use
ReplyDeleteval(mystringvalue,myrealvalue,myinteger)
then if myinteger is 0 you are good to go with the conversion of the string to integer (ok real)
Looks not so bad to me. What it does is actually refinining a string that contains an integer: removes blanks, etc. The code of all the commenters just does something different. My version would be like this:
ReplyDeletefunction RefineIntString(const s: string): string;
var
i: integer;
begin
If TryStrToInt(s, i) then
result = IntToStr(i)
else
result := '';
end;
Exceptions are slow and annoying in the debugger if they are applied thousands of times. And I would say that I can predict the outcome of trim ('') - and trimming twice is double work and never produces a newly allocated string that will be saved, and inttostr (strtoint ()) will generate a new string that might have the same content as value. The code can be made at least 100 times faster, much more readable and much easier to debug.
ReplyDeleteI don't like exceptions and prefer more "c stdlib" like functions..>
ReplyDeletefunction StrToIntDef ( const IntegerString : string; Default : Integer ) : Integer;