< .Net Type, Variable & Operator 10 | Index #1 | Index # 2 | C++ .NET Formatting 2 >


 

 

Playing With C++ .NET Formatting 1

 

 

The following are all the topics available in this module that consist of nine parts. All codes supposed to be based on the new C++ .NET syntaxes.

 

  1. Introduction

  2. Format Specifiers

  3. Numeric Format Strings

  4. Parsing and Format Specifiers

  5. ToString and Format Specifiers

  6. Formatting Base Types

  7. Format Providers

  8. Composite Formatting

  9. Format Item Syntax

  10. Format Item Components

  11. Index Component

  12. Alignment Component

  13. Format String Component

  14. Escaping Braces

  15. Processing Order

------------Next--------------------------

  1. Standard Numeric Format Strings

  2. Standard Numeric Format Strings Output Examples

  3. Custom Numeric Format Strings

  4. Date and Time Format Strings

  5. Standard DateTime Format Strings

  6. Custom DateTime Format Strings

  7. Enumeration Format Strings

  8. Customizing Format Strings

  9. Adding Custom Format Strings for Custom Types

  10. Adding Custom Format Strings to Existing Types

  11. DateTimeFormatInfo Class Example

 

 

Introduction

 

The .NET Framework provides a customizable, general-purpose formatting mechanism to convert a value into a string suitable for display. For example, a numeric value can be formatted in hexadecimal, scientific notation, or a series of digits separated into groups with a user-specified punctuation mark. Dates and times can be formatted as appropriate for a particular country, region, or culture. An enumerated constant can be formatted as its numeric value or its name.

You control formatting by specifying a format string and format provider, or by using the defaults. A format string contains one or more format specifier characters that indicate how a value is to be converted. A format provider supplies additional control, replacement, and cultural information required to convert a specific type. You can override the way the .NET Framework interprets a format string by implementing the IFormattable interface, provide your own format provider by implementing the IFormatProvider interface, and perform your own formatting by implementing the ICustomFormatter interface. The .NET Framework provides a feature called composite formatting that uses one or more format strings to embed one or more formatted values in a result string. The result string can be used for further processing, displayed to the system console, or written to a stream.

 

Format Specifiers

 

The .NET Framework defines standard and custom format specifiers for formatting numbers, dates and times, and enumerations. Format specifiers are used by various methods that format output strings, such as Console::WriteLine and the ToString method of any type, and some methods that parse input strings, such as DateTime::ParseExact.

 

Numeric Format Strings

 

Numeric format strings are used to control the formatting produced when a numeric data type is represented as a string. The overloads of ToString that exist in all numeric types can be used with one of the numeric data types to control the precise behavior when converting a numeric type to a string. Additionally, numeric format strings can be used in conjunction with methods in several classes like Console and StreamWriter to format text. Numeric format strings fall into one of two categories: standard format strings and custom format strings. Note that regardless of the format string, if a floating-point type (Single or Double) is positive or negative infinity, or NaN (Not a Number), the formatted string is the value of the respective PositiveInfinitySymbol, NegativeInfinitySymbol, or NaNSymbol specified by the currently applicable NumberFormatInfo object.

 

Parsing and Format Specifiers

 

Formatting converts the value of a type into a string representation; parsing, the inverse of formatting, creates a data type from a string representation. A format provider governs how parsing is performed, and some methods, such as DateTime.ParseExact, take a format specifier parameter that indicates the expected format of the string representation.

 

ToString and Format Specifiers

 

The .NET Framework supports overloading the default ToString method for a type, which performs rudimentary formatting, with a specialized version of ToString that uses a format specifier parameter to indicate how the value is to be formatted. Study the following example.

// Format.cpp : main project file.

// Example of Convert::ToString(non-numeric types, IFormatProvider)

#include "stdafx.h"

 

using namespace System;

using namespace System::Globalization;

 

#define null (Object^)0

 

// An instance of this class can be passed to methods that require

// an IFormatProvider.

ref class DummyProvider: public IFormatProvider

{

  public:

   // Normally, GetFormat() returns an object of the requested type

   // (usually itself) if it is able; otherwise, it returns Nothing.

   virtual Object^ GetFormat(Type^ argType)

   {

      // Here, the type of argType is displayed, and GetFormat

      // always returns Nothing.

      Console::Write("{0,-40}", argType->ToString());

      return null;

   }

};

 

int main()

{

   // Create an instance of the IFormatProvider.

   DummyProvider^ provider = gcnew DummyProvider;

   String^ converted;

   // Convert these values using DummyProvider.

   int Int32A = -2323232323;

   double DoubleA = 888888.7777;

   Object^ ObjDouble =  -98989.4321;

   DateTime DayTimeA = DateTime(2005,10,22,11,35,22);

   bool BoolA = true;

   String^ StringA = "Some strings";

   Char CharA = '$';

   TimeSpan TSpanA = TimeSpan(0,14,0);

 

   Object^ ObjOther = static_cast<Object^>(provider);

   Console::WriteLine("This example of "

   "Convert::ToString(non-numeric, IFormatProvider* ) \n"

   "generates the following output. The provider type, "

   "argument type, \nand argument value are displayed.");

   Console::WriteLine("\nNote: The IFormatProvider object is "

   "not called for Boolean, String, \nChar, TimeSpan, "

   "and non-numeric Object.");

   // The format provider is called for these conversions.

   Console::WriteLine();

   converted = Convert::ToString(Int32A, provider);

   Console::WriteLine("int      {0}", converted);

   converted = Convert::ToString( DoubleA, provider);

   Console::WriteLine("double   {0}", converted);

   converted = Convert::ToString( ObjDouble, provider);

   Console::WriteLine("Object   {0}", converted);

   converted = Convert::ToString( DayTimeA, provider);

   Console::WriteLine("DateTime {0}", converted);

   // The format provider is not called for these conversions.

   Console::WriteLine();

   converted = Convert::ToString(BoolA, provider);

   Console::WriteLine("bool     {0}", converted);

   converted = Convert::ToString(StringA, provider);

   Console::WriteLine("String   {0}", converted);

   converted = Convert::ToString(CharA, provider);

   Console::WriteLine("Char     {0}", converted);

   converted = Convert::ToString(TSpanA, provider);

   Console::WriteLine("TimeSpan {0}", converted);

   converted = Convert::ToString(ObjOther, provider);

   Console::WriteLine("Object   {0}", converted);

}

 

Output:

C++ .NET formatting - Example of Convert::ToString(non-numeric types, IFormatProvider)

 

Formatting Base Types

 

Use formatting to convert a standard .NET Framework data type to a string that represents that type in some meaningful way. For example, if you have an integer value of 100 that you want to represent as a currency value, you can use the ToString method and the currency format string ("C") to produce a string of "$100.00". Note that computers that do not have U.S. English specified as the current culture will display whatever currency notation is used by the current culture. To format a base type, pass the desired format specifier, the desired format provider, or both to the ToString method of the object you want to format. If you do not specify a format specifier, or if you pass null (Nothing in Visual Basic), then "G" (the general format) is used as the default. If you do not specify a format provider, if you pass null (Nothing), or if the provider you specify does not have the property pertaining to the requested action, the format provider associated with the current thread is used.

 

Format Providers

 

Format providers supply information such as the character to use as the decimal point when formatting numeric strings, or the separation character to use when formatting a DateTime object. Format providers define the characters used for formatting by the format specifiers, but do not define the specifiers themselves. A format provider can either be passed to the overload of ToString required by the IFormattable interface, or be predetermined by the method you are using to format text if no format provider is passed. When no format provider is passed, the information is either inferred, or obtained from one of the standard format providers included in the .NET Framework. Generally, classes that implement IFormattable also provide overloads of ToString that accept only a format specifier or only a format provider. The default ToString method, which accepts no parameters, is inherited from the Object class.

 

Composite Formatting

 

The .NET Framework composite formatting feature, which is supported by methods such as String.Format and the output methods of System::Console and System::IO::TextWriter, replaces each indexed format item embedded in a source string with the formatted equivalent of a corresponding element in a list of values. The .NET Framework composite formatting feature enables you to provide a list of values and a source string consisting of alternating fixed text and indexed placeholders, and easily obtain a result string consisting of the original fixed text intermixed with formatted values. Use composite formatting with methods such as String.Format, which returns a formatted string, Console::WriteLine, which displays the result string to the console, or an implementation of TextWriter::WriteLine, which writes the result string to a stream or file. Each indexed placeholder, or format item, corresponds to one element in a list of values. The composite formatting feature returns a new result string where each format item embedded in the source string is replaced by the corresponding formatted value. The source string consists of zero or more runs of fixed text interrupted by one or more format items. The fixed text can contain any content you choose.

String ^ myName = "Fred";

String::Format("Name = {0}, hours = {1:hh}", myName, DateTime::Now);

The fixed text is "Name = " and ", hours = ". The format items are "{0}" and "{1:hh}". The list of values is myName and DateTime::Now.

 

Format Item Syntax

 

Each format item takes the following form.

{index[,alignment][:formatString]}

For example:

Console::WriteLine("Total: {0,8:c}", mybillTotal);

The matching braces ("{" and "}") are required.

 

Format Item Components

 

A format item consists of the following components.

 

Index Component

 

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding element in the list of values. That is, the format item whose parameter specifier is 0 formats the first value in the list, the format item whose parameter specifier is 1 formats the second value in the list, and so on. Multiple format items can refer to the same element in the list of values by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific and number format by specifying a source string like this:

 "{0:X} {0:E} {0:N}"

Each format item can refer to any parameter. For example, if there are three values, you can format the second, first, and third value by specifying a source string like this: "{1} {0} {2}". A value that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of values.

 

Alignment Component

 

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

 

Format String Component

 

The optional formatString component consists of standard or custom format specifiers. If formatString is not specified, the general ("G") format specifier is used. The colon is required if formatString is specified.

 

Escaping Braces

 

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported. The way escaped braces are interpreted can lead to unexpected results. For example, consider the format item:

"{{{0:D}}}"

which is intended to display an opening brace, a numeric value formatted as a decimal number, and a closing brace. However, the format item is actually interpreted in the following manner:

 

  1. The first two opening braces ("{{") are escaped and yield one opening brace.

  2. The next three characters ("{0:") are interpreted as the start of a format item.

  3. The next character ("D") would be interpreted as the Decimal standard numeric format specifier, but the next two escaped braces ("}}") yield a single brace. Because the resulting string ("D}") is not a standard numeric format specifier, the resulting string is interpreted as a custom format string that means display the literal string "D}".

  4. The last brace ("}") is interpreted as the end of the format item.

  5. The final result that is displayed is the literal string, "{D}". The numeric value that was to be formatted is not displayed.

 

One way to write your code to avoid misinterpreting escaped braces and format items is to display the braces and format item separately. That is, display an opening brace, then the result of the format item, then a closing brace.

 

 

 

 

 

Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7 | Part 8 | Part 9


< .Net Type, Variable & Operator 10 | Index #1 | Index # 2 | C++ .NET Formatting 2 >