formatting and parsing. slide 2 introduction two core topics parsing - converting strings to other...
TRANSCRIPT
Formatting and Parsing
Slide 2
Introduction Two core topics
Parsing - Converting strings to other types (numbers, dates, …)
Formatting Converting those same other types back to strings
Slide 3
Formatting You have seen how to call ToString()
to format a number or date Here, we delve much deeper into
formatting
Slide 4
Formatting Numeric Values as Strings There are a couple of ways to format
data Call the String.Format method
The first argument contains the “format string”
The second argument contains the value to format
Call the ToString() method of a numeric or DateTime data type
Slide 5
Formatting Numeric Values as Strings (2) Applying custom formatting
Use predefined format strings Use the NumberFormatInfo
Slide 6
The NumberFormatInfo Class Culture invariant information to format
and parse numbers Properties
To define currency formatting characters and precisions
Separators (decimal / percent) Positive / negative pattern and sign
Slide 7
String.Format A format string contains
Literal text, Placeholders that contain the formatted values Placeholders have the syntax
{index[,alignment][:formatString]} index is a value from 0 to n marking the placeholder
number alignment contains the minimum width of the
formatted value Negative values are left justified
format string contains the format specifiers
Slide 8
String.Format (Example)s = String.Format(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
Console.WriteLine(s);
Slide 9
Using ToString() Call ToString on the numeric data type The format specifier is passed as an
argument Example:
txtOutputString.Text =
i.ToString(“0:C”);