0

EveryOne I need some esay way to change from integer and string in delphi 7

var 
Str:String;
Int:Integer;
// Here what i need to do
Str:='123';
Int:=Str.AsInteger
// or use this
Int:=123;
Str=Int.AsString;
3
  • 1
    For unsafe casting use StrToInt function, for safe casting e.g. TryStrToInt. Commented Jan 20, 2014 at 8:24
  • 1
    To add to TLama - there is also StrToIntDef Commented Jan 20, 2014 at 8:30
  • 1
    And the reverse transformation: stackoverflow.com/questions/14317264 - for the SO inter-connectivity Commented Jan 20, 2014 at 8:39

3 Answers 3

9

The easiest way is to use these two methods:

IntVal := StrToInt(StrVal);    // will throw EConvertError if not an integer
StrVal := IntToStr(IntVal);    // will always work

You can also use the more fault-tolerant TryStrToInt (far better than catching EConvertError):

if not TryStrToInt(StrVal, IntVal) then
  begin
  // error handling
  end;

If you want to resort to a default value instead of handling errors explictly you can use:

IntVal := StrToIntDef(StrVal, 42);    // will return 42 if StrVal cannot be converted
Sign up to request clarification or add additional context in comments.

Comments

4

If you're using a recent version of Delphi, in addition to the previous answers, you can alternatively use a pseudo-OOP syntax as you wanted to originally - the naming convention is just ToXXX not AsXXX:

Int := Str.ToInteger
Str := Int.ToString;

The Integer helper also adds Parse and TryParse methods:

Int := Integer.Parse(Str);
if Integer.TryParse(Str, Int) then //...

7 Comments

Why do you say "pseudo" here? It looks pretty plain OOP syntax to me.
I meant to the extent strings and integers remain not objects in any proper OOP sense (there's no inheritance etc.)
I would not say that inheritance is needed for OOP. Consider a value type to be a sealed class.
@DavidHeffernan: There wouldn't have been any Create to either Str or Int, though. Implicit instantiation? Well, whatever. :)
@AndriyM std::string str;
|
1

You can use:

StrToInt(s)

and

IntToStr(i)

functions.

1 Comment

thank you but i dont need as that ...! look this exsample. type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure Button1Click(Sender: TObject); end; Integer = class FValue: System.Integer; function ToString: string; public property Value: System.Integer read FValue write FValue; end; var Form1: TForm1; implementation function Integer.ToString: string; begin Str(FValue, Result); end; procedure TForm1.Button1Click(Sender: TObject); var op:integer; begin op.Value:=45; Edit1.Text:=op.ToString; end; end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.