Changing the data type
A number in an Edit is really text, so it must be converted to a number before calculating: Delphi does not allow an expression of one type to be given directly to a variable of another type. StrToInt (text to number) and IntToStr (number to text) are used for integers, StrToFloat and FloatToStr for real numbers. Intermediate results of a calculation are stored in variables: they are declared in the var section under the procedure header, for example var r: Real; or var i, m, n, s: Integer; Such a variable is local: it works only inside this procedure and disappears when the procedure ends. If a letter is typed in an Edit instead of a number, or a real number uses the wrong separator (a comma instead of a point or the other way round), StrToInt and StrToFloat show an error message, so tell the user in a Label how to type. FloatToStr gives the result with the separator of the computer settings.
| Function | Job |
|---|---|
| StrToInt | text → integer |
| IntToStr | integer → text |
| StrToFloat | text → real number |
| FloatToStr | real number → text |
In a simple calculator app a pupil typed 12 and 3 in two boxes, but the program took them as text and showed “123”. After the text was converted to numbers, the result was 15. What is typed in a box is always text, and it must be converted to a number before calculating.
Programmers, people who work with spreadsheets and data engineers choose data types correctly to avoid wrong results.
On paper write three things made of digits that you would never add together (such as a phone number, a house number, a class number) and three that you would add (such as pages read), and say which a program should treat as text.
1procedure TForm1.Button1Click(Sender: TObject); 2var a: Integer; 3begin 4 a := StrToInt(Edit1.Text); 5 Label1.Caption := 'Hajm: ' + IntToStr(a * a * a); 6 Label2.Caption := 'Sirt: ' + IntToStr(6 * a * a); 7end;
1procedure TForm1.Button2Click(Sender: TObject); 2var i, n, f: Integer; 3begin 4 n := StrToInt(Edit2.Text); 5 f := 1; 6 for i := 1 to n do 7 f := f * i; 8 Label3.Caption := 'Faktorial: ' + IntToStr(f); 9end;
“The calculator”: a pair builds an application with two Edits; a button shows the sum, difference and product in three Labels; they test what message the application gives for a wrong entry.