Practical Programming COMP153-08A Lecture 4:Strings & Formatting
Tools -> Options
Programming So Far First: Controls, Properties, Events Second: Types and Arithmetic Third: Variables and some Input/Output Today: –Strings & Formatting
Consider this code Dim x As Integer x = Val(TextBox1.Text) TextBox2.Text = Str(x) Use x = and x = 12.51
Formatting Input To be more “precise” we use: Convert: –Dim x As Integer –x = Convert.ToInt32(TextBox1.Text) –We can ToDouble, ToInt16 (short), ToSingle, ToDouble.
Example Dim x, y As Integer x = Convert.ToInt32(TextBox1.Text) y = Convert.ToInt32(TextBox2.Text) Label1.Text = Str(x) & Str(y) Label2.Text = Str(x) + Str(y) Label3.Text = x.ToString + y.ToString Label4.Text = x.ToString & y.ToString
Example in action
Formatting output Numeric –Generally: VARNAME.ToString(formatString) Examples – currency format (“c”) Dim price As Single price = Val(TextBox1.Text) Label1.Text = price.ToString("C")
Price Example
Decimal Places Change the “C” to “N2” (for two decimal places) Dim price As Single price = Val(TextBox1.Text) Label1.Text = price.ToString(“N2")
Percentage Change to “P” Dim price As Single price = Val(TextBox1.Text) Label1.Text = price.ToString(“P")
Strings Strings have many associated methods –Dim s As String = “I am a string” –MessageBox.Show(s.Length) Strings and spacing –Dim s As String = “123” –Label1.Text = s –Label2.Text = s.PadLeft(5) –Label3.Text = s.PadLeft(10) –Can also use PadRight
Padding to total length
Bigger Example
Solution Dim x, y As Integer x = Val(TextBox1.Text) y = Val(TextBox2.Text) Label1.Text = "Mod of " & x & " " & y & " = " & x Mod y Label2.Text = "Exp of " & x & " " & y & " = " & x ^ y Label3.Text = "Div of " & x & " " & y & " = " & x \ y Label4.Text = "Concat of " & x & " " & y & " = " & Str(x) + Str(y)
Test on Friday 9-11 in Lab 3 9 questions (40 marks) Topics –Computer components (4) –Controls (2) –Setting properties (4) –Setting properties 2 (4) –Events (6) –Arithmetic 1 (4) –Types (4) –Arithmetic 2 (10) –Formatting (2)
THE END of the lecture