|
How to
Use Formatting to Represent Types as Strings and
Parsing
to Convert a String to a Type |
|
description |
This
article uses Visual Basic to introduce the basic format and
parse mechanisms in Microsoft.NET. |
|
environment |
VS2002, VS2003, VS2005 |
|
language
|
Visual Basic |
|
tags |
format, parse, string, type |
Updated: 11/20/2006
This article introduces the basic
format and parse mechanisms in Microsoft.NET.
Formatting
The .NET Framework provides a
consistent, flexible, and comprehensive means for you to represent
any of the numeric, enumeration, and date and time base data types
as a string. Formatting is controlled by strings of format specifier
characters that indicate how a base type value is to be represented.
For example, format specifiers indicate whether a formatted number
should be represented in scientific notation, or whether a formatted
date should present the month as a number or a name.
You can use format without using parse to
display an non-editable result e.g. in a Label or in a report. In this
case you are only presenting data to the user; you are not giving the
user the ability to edit the data.
More common is the use of format and parse
together. Consider a data entry form that is used to access and modify
data in a database.
1. User searches and selects an existing
record in the database.
2. The application pulls the record into
the data entry form.
3. Instead of showing unformatted numbers
from the database, the application formats each number into human readable
form.
4. User modifies a number through a
TextBox. The user enters unformatted numbers. When the user finishes a
TextBox edit the application once again formats the number into human
readable form.
5. User saves the edits. The application
parses the numbers into .Net Framework types before updating the database.
Format Specifiers
Formatting in the .Net Framework is
implemented using format specifiers which are more commonly called “format
strings”
There are standard and custom format
strings.
Standard format strings are used by the
ToString methods of the .Net Framework types Int32, Int64, Single, Double,
Enumeration, and DateTime.
EXAMPLE: Date Type Standard Format Strings
The Date type
implements standard format strings through its ToString methods.
Dim
currentDateTime As
Date = Now
' Use
some of the Date type ToString methods
' to
format a .Net Framework Date type
' into
human readable form.
Console.WriteLine(currentDateTime.ToString)
RESULT: 6/20/2003
1:12:40 PM
Console.WriteLine(currentDateTime.ToLongDateString)
RESULT: Friday, June
20, 2003
Console.WriteLine(currentDateTime.ToShortDateString)
RESULT: 6/20/2003
EXAMPLE: Numeric Type Standard Format
Strings
Numeric types implement standard format
strings through their ToString methods.
Dim
aDouble As Double
' Use
some of the numeric standard format strings
' to
format a .Net Framework Double type
' into
human readable form.
'
Format as currency.
aDouble = 19758.1001
Console.WriteLine(aDouble.ToString("C"))
RESULT: $19,758.10
'
Format as percentage.
aDouble = 0.0812
Console.WriteLine(aDouble.ToString("P"))
RESULT:
8.12 %
Visit the links below to learn more about
standard format strings:
Microsoft.NET 1.x
Standard Numeric Format Strings
Standard DateTime Format Strings
Standard Enumeration Format Strings
Microsoft.NET 2.0
Standard Numeric Format Strings
Standard DateTime Format Strings
Standard Enumeration Format Strings
Custom
Format Strings
Custom format strings
are created from custom format characters. Visit the link below for
listings of some of the custom format characters you can use to build
custom format strings.
Microsoft.NET 1.x
Custom Numeric Format Strings
Custom Datetime Format Strings
Microsoft.NET 2.0
Custom Numeric
Format Strings
Custom Enumeration Format Strings
Here is an example that
uses Custom Numeric Format Strings to format a Double value to a string
representing a telephone number
'
Create a Double
Dim
aDouble As Double
= 1234567890
' Use
Numeric Custom Format Characters to
'
display the Double as a telephone number.
Dim
phoneNumber As
String = aDouble.ToString("(###) ### - ####")
Console.WriteLine(phoneNumber)
RESULT: (123) 456 -
7890
The “#” character is the
custom numeric format digit placeholder character. 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 output string.
Here is an example that
uses Custom Datetime Format Strings to format a Datetime value to provide
a unique way to represent a date as a string.
'
Create a Datetime
Dim
aDateTime As DateTime = Now
' Use
DateTime Custom Format Characters to
'
display the DateTime in a unique format.
Dim
uniqueDateTime As
String = aDateTime.ToString("dddd - d - MMMM")
Console.WriteLine(uniqueDateTime)
RESULT: Friday - 1 –
August
The example combined
three custom format strings with two literal dash (-) characters:
dddd
Displays the
full name of the day for the specified DateTime.
d Displays
the current day of the month, measured as a number between 1 and 31,
inclusive. If the day is a single digit only (1-9), then it is displayed
as a single digit. Note that if the’d’ format specifier is used alone,
without other custom format strings, it is interpreted as the standard
short date pattern format specifier. If the 'd' format specifier is passed
with other custom format specifiers or the '%' character, it is
interpreted as a custom format specifier.
MMMM
Displays the full name of the month for the specified DateTime.
Both examples
demonstrate how custom format characters are combined to create a custom
format string. By passing in the custom format string as an argument to a
ToString method call, you can create output that is formatted exactly as
you want it.
Parsing
Parsing is the opposite
of formatting – it is converting a human readable string representation
back into a machine readable .Net Framework base type. For example,
convert a date displayed in string format in a Windows Form like this:
September 1, 2003; to a .Net Framework DateTime object.
Example: Parse a string
representation of a date to a DateTime object.
'
Create a string that represents a date.
Dim
dateString As
String = "September 1, 2003"
'
Declare a variable of type DateTime named aDate.
Dim
aDate As DateTime
'
Assign a reference to a DateTime object created
' by
parsing the string representation of a date
' to
the aDate variable.
aDate =
DateTime.Parse(dateString)
Console.WriteLine(aDate)
Result: 9/1/2003
12:00:00 AM
The parsing method used
is determined by the .Net Framework base type object to be created from a
string. There are six main parsing methods: Numeric, Date, Time,
Enumeration, Char, and Boolean. The link below leads to details about
each.
Parsing Strings .NET 1.x
Parsing Strings
.NET 2.0
Some parsing methods
have variations which help control how a string is converted into a .Net
Framework base type. For example, when parsing to a number, the
Globalization NumberStyles flags are used to parse a string that contains
non-numeric characters such as a currency symbol, a decimal point, an
exponent, parentheses, and so on.
Example: Parse a string
representation of a number that contains non-numeric characters.
'
Create a string that represents a decimal number that contains non-numeric
characters.
Dim
aNumberString As
String = "$123,456.56"
'
Declare a variable of type Decimal named aDecimal.
Dim
aDecimal As
Decimal
'
Assign a reference to a Decimal object created
' by
parsing the string representation of a date,
' that
includes non-numeric characters,
' to
the aDecimal variable.
'
' Use
Globalization.NumberStyle flags
' to
allow for thousands group sepearators,
' a
currency symbol, and a decimal point
' that
may be included in the the string
'
representing a decimal number.
aDecimal =
Decimal.Parse(aNumberString, _
Globalization.NumberStyles.Number.AllowThousands _
Or
Globalization.NumberStyles.Number.AllowCurrencySymbol _
Or
Globalization.NumberStyles.AllowDecimalPoint)
Console.WriteLine(aDecimal)
Result: 123456.56
|