< C++ .NET Formatting 3 | Index #1 | Index # 2 | C++ .NET Formatting 5 >


 

 

Playing With C++ .NET Formatting 4

 

 

The following are the topics available in this part.

  1. Custom Numeric Format Strings

  2. Date and Time Format Strings

 

 

Custom Numeric Format Strings

 

If the standard numeric format specifiers do not provide the type of formatting you require, you can use custom format strings to further enhance string output. A standard format string consists of a single alphabetic character optionally followed by a sequence of digits that form a value between 0 and 99; all other format strings are custom format strings. The following table shows the characters you can use to create custom numeric format strings and their definitions. Note that the result strings produced by some of these characters are influenced by the settings in the Regional Options control panel of the NumberFormatInfo object associated with the current thread. Computers using different cultures will generate different result strings.

 

Format character

Name

Description

0

Zero placeholder

If the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the result string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the result string. The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.

#

Digit placeholder

If the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. Note that this specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed. The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.

.

Decimal point

The first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo that controls formatting.

,

Thousand separator and number scaling

The ',' character serves two purposes. First, if the format string contains a ',' character between two digit placeholders (0 or #) and to the left of the decimal point if one is present, then the output will have thousand separators inserted between each group of three digits to the left of the decimal separator. The actual character used as the decimal separator in the result string is determined by the NumberGroupSeparator property of the current NumberFormatInfo that controls formatting.

Second, if the format string contains one or more ',' characters immediately to the left of the decimal point, then the number will be divided by the number of ',' characters multiplied by 1000 before it is formatted. For example, the format string "0,," will represent 100 million as simply 100. Use of the ',' character to indicate scaling does not include thousand separators in the formatted number. Thus, to scale a number by 1 million and insert thousand separators you would use the format string "#,##0,,".

%

Percentage placeholder

The presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.

E0

E+0

E-0

e0

e+0

e-0

Scientific notation

If any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the format string and are followed immediately by at least one '0' character, then the number is formatted using scientific notation with an 'E' or 'e' inserted between the number and the exponent. The number of '0' characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The "E+" and "e+" formats indicate that a sign character (plus or minus) should always precede the exponent. The "E", "E-", "e", or "e-" formats indicate that a sign character should only precede negative exponents.

\

Escape character

In C# and C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like '\n' (new line).

In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display '\'. Note that this escape character is not supported in Visual Basic; however, ControlChars provides the same functionality.

'ABC'

"ABC"

Literal string

Characters enclosed in single or double quotes are copied to the result string literally, and do not affect formatting.

;

Section separator

The ';' character is used to separate sections for positive, negative, and zero numbers in the format string.

Other

All other characters

All other characters are copied to the result string as literals in the position they appear.

 

Table 3

 

Note that for fixed-point format strings (strings not containing an "E0", "E+0", "E-0", "e0", "e+0", or "e-0"), numbers are rounded to as many decimal places as there are digit placeholders to the right of the decimal point. If the format string does not contain a decimal point, the number is rounded to the nearest integer. If the number has more digits than there are digit placeholders to the left of the decimal point, the extra digits are copied to the result string immediately before the first digit placeholder. Different formatting can be applied to a string based on whether the value is positive, negative, or zero. To produce this behavior, a custom format string can contain up to three sections separated by semicolons:

  1. One section: The format string applies to all values.

  2. Two sections: The first section applies to positive values and zeros, and the second section applies to negative values. If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, then the resulting zero is formatted according to the first section.

  3. Three sections: The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros. The second section might be left empty (by having nothing between the semicolons), in which case the first section applies to all nonzero values. If the number to be formatted is nonzero, but becomes zero after rounding according to the format in the first or second section, then the resulting zero is formatted according to the third section.

This type of formatting ignores any preexisting formatting associated with a number when the final value is formatted. For example, negative values are always displayed without a minus sign when section separators are used. If you want the final formatted value to have a minus sign, you should explicitly include the minus sign as part of the custom format specifier. The following example illustrates how section separators can be used to produce formatted strings.

 

// testprog.cpp : main project file.

 

#include "stdafx.h"

 

using namespace System;

using namespace System::Globalization;

 

int main()

{

  double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0;

  // In the U.S. English culture, MyString has the value: $19.95.

  String^ MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero");

  Console::Write("MyPos.ToString(\"$#,##0.00;($#,##0.00);Zero\") -> ");

  Console::WriteLine(MyString);

  // In the U.S. English culture, MyString has the value: ($19.95).

  // The minus sign is omitted by default.

  MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero");

  Console::Write("MyNeg.ToString(\"$#,##0.00;($#,##0.00);Zero\") -> ");

  Console::WriteLine(MyString);

  // In the U.S. English culture, MyString has the value: Zero.

  MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero");

  Console::Write("MyZero.ToString(\"$#,##0.00;($#,##0.00);Zero\") -> ");

  Console::WriteLine(MyString);

  return 0;

}

 

Output :

 

 

 

 

C++ .Net formatting - code example that illustrates how section separators can be used to produce formatted strings

 

The following example demonstrates custom number formatting.

// testprog.cpp : main project file.

 

#include "stdafx.h"

 

using namespace System;

using namespace System::Globalization;

 

int main()

{

  Double myDouble = 1234567890;

  String^ myString = myDouble.ToString("(###) ### - ####");

  // The value of myString is "(123) 456 – 7890".

  Console::WriteLine(myString);

 

  int  MyInt = 100;

  myString = MyInt.ToString("My Number = #");

  // In the U.S. English culture, MyString has the value:

  // "My Number = 100".

  Console::WriteLine(myString);

 

      return 0;

}

 

Output:

C++ .Net formatting - code example that demonstrates custom number formatting

 

The following table illustrates the output created by applying some custom numeric format strings to specific data types and values. Output was generated using the ToString method and the U.S. English culture. The Format column indicates the format string, the Data type column indicates the data type used, the Value column indicates the value of the number being formatted, and the Output column indicates the result of formatting.

 

Format

Data type

Value

Output

#####

Double

123

123

00000

Double

123

00123

(###) ### - ####

Double

1234567890

(123) 456 – 7890

#.##

Double

1.2

1.2

0.00

Double

1.2

1.20

00.00

Double

1.2

01.20

#,#

Double

1234567890

1,234,567,890

#,,

Double

1234567890

1235

#,,,

Double

1234567890

1

#,##0,,

Double

1234567890

1,235

#0.##%

Double

0.086

8.6%

0.###E+0

Double

86000

8.6E+4

0.###E+000

Double

86000

8.6E+004

0.###E-000

Double

86000

8.6E004

[##-##-##]

Double

123456

[12-34-56]

##;(##)

Double

1234

1234

##;(##)

Double

-1234

(1234)

 

Table 4

 

Date and Time Format Strings

 

DateTime format strings are used to control the formatting produced when a date or time is represented as a string.

The DateTime data type implements IFormattable, allowing it to be formatted as a string with one of the overloads of DateTime.ToString. The output of the standard format strings is influenced by the current culture. The standard .NET Framework format provider class is DateTimeFormatInfo, which can be obtained from a passed CultureInfo object or the one associated with the current thread.

DateTime format strings fall into two categories: standard format strings and custom format strings. The custom format strings allow DateTime objects to be formatted for situations where the standard formatting strings are not useful.

// testprog.cpp : main project file.

// This code example demonstrates the String.Format() method.

// Formatting for this example uses the "en-US" culture.

 

#include "stdafx.h"

 

using namespace System;

 

enum class Color {Yellow = 1, Blue, Green};

 

int main()

{

      DateTime thisDate = DateTime::Now;

      // Store the output of the String.Format method in a string.

      String^ s = "";

      Console::Clear();

      // Format a negative integer or floating-point number in various ways.

      Console::WriteLine("Standard Numeric Format Specifiers");

      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);

      // Format the current date in various ways.

      Console::WriteLine("Standard DateTime Format Specifiers");

      s = String::Format(

        "(d) Short date: . . . . . . . {0:d}\n"

        "(D) Long date:. . . . . . . . {0:D}\n"

        "(t) Short time: . . . . . . . {0:t}\n"

        "(T) Long time:. . . . . . . . {0:T}\n"

        "(f) Full date/short time: . . {0:f}\n"

        "(F) Full date/long time:. . . {0:F}\n"

        "(g) General date/short time:. {0:g}\n"

        "(G) General date/long time: . {0:G}\n"

        "    (default):. . . . . . . . {0} (default = 'G')\n"

        "(M) Month:. . . . . . . . . . {0:M}\n"

        "(R) RFC1123:. . . . . . . . . {0:R}\n"

        "(s) Sortable: . . . . . . . . {0:s}\n"

        "(u) Universal sortable: . . . {0:u} (invariant)\n"

        "(U) Universal sortable: . . . {0:U}\n"

        "(Y) Year: . . . . . . . . . . {0:Y}\n", thisDate);

      Console::WriteLine(s);

      // Format a Color enumeration value in various ways.

      Console::WriteLine("Standard Enumeration Format Specifiers");

      s = String::Format(

        "(G) General:. . . . . . . . . {0:G}\n"

        "    (default):. . . . . . . . {0} (default = 'G')\n"

        "(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n"

        "(D) Decimal number: . . . . . {0:D}\n"

            "(X) Hexadecimal:. . . . . . . {0:X}\n", Color::Green);

      Console::WriteLine(s);

 

      return 0;

}

 

Output:

C++ .Net formatting - This code example demonstrates the String.Format() method

 

 

 

 

 

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


< C++ .NET Formatting 3 | Index #1 | Index # 2 | C++ .NET Formatting 5 >