Download presentation
Presentation is loading. Please wait.
Published byMorris Ferguson Modified over 9 years ago
1
Formatting and Parsing
2
Slide 2 Introduction Two core topics Parsing - Converting strings to other types (numbers, dates, …) Formatting Converting those same other types back to strings
3
Slide 3 Formatting You have seen how to call ToString() to format a number or date Here, we delve much deeper into formatting
4
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
5
Slide 5 Formatting Numeric Values as Strings (2) Applying custom formatting Use predefined format strings Use the NumberFormatInfo
6
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
7
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
8
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);
9
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”);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.