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;

Comments

  1. Are you sure this is actual code and not a Zen session? :-)

    ReplyDelete
  2. That's nice - put it on docwiki! :p

    ReplyDelete
  3. Is there a prize? I could offer up some real stunners. ;)

    ReplyDelete
  4. I like to use
    val(mystringvalue,myrealvalue,myinteger)
    then if myinteger is 0 you are good to go with the conversion of the string to integer (ok real)

    ReplyDelete
  5. 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:
    function RefineIntString(const s: string): string;
    var
      i: integer;
    begin
      If TryStrToInt(s, i) then 
        result = IntToStr(i)
      else
        result := '';
    end;

    ReplyDelete
  6. 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.

    ReplyDelete
  7. I don't like exceptions and prefer more "c stdlib" like functions..>

    function StrToIntDef ( const IntegerString : string; Default : Integer ) : Integer;

    ReplyDelete

Post a Comment