Formatting Numbers, Dates, and Strings With The Format Function
Formatting Numbers, Dates, and Strings With The Format Function
The Format function returns a string containing an expression formatted according to instructions contained in a format expression. This function is
useful for formatting numeric, date, time, and string data.
Part Description
Expression Required. Any valid expression.
Style Optional. A valid named or user-defined format String expression.
FORMATTING NUMBERS
Numbers can be formatted in many ways, using either Named (Pre-Defined) formats or Custom formats.
The above named numeric formats for the Format function were also available in earlier versions of VB. New in .NET are the single letter
abbreviations for the first six items shown above. Two new formats in this category have been introduced in .NET:
"D" or "d" Displays number as a string that contains the value of the number in Decimal (base 10) format. This option is
supported for integral types (Byte, Short, Integer, Long) only.
"X" or "x" Displays number as a string that contains the value of the number in Hexadecimal (base 16) format. This
option is supported for integral types (Byte, Short, Integer, Long) only.
To demonstrate the named numeric formats described above, create a new "Try It" project, and place the following code in Sub Main:
In addition to the named numeric formats described previously, you can also create custom numeric formats using a combination of specific
characters recognized by the Format function. To format numbers, combinations of the following characters can be used:
Format Character
Description
0 Digit placeholder Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, dis
position. If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading o
number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format ex
number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there ar
the decimal separator in the format expression, display the extra digits without modification.
# Digit placeholder Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, di
position. This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the s
than there are # characters on either side of the decimal separator in the format expression.
. Decimal The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format express
placeholder number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. If you always want a leading zero disp
numbers, use 0 as the first digit placeholder to the left of the decimal separator instead. (Note: In some locales, a comma is used as t
The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your syste
% Percent The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.
placeholder
, (comma) Thousand The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal s
separator of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adja
separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means "sc
dividing it by 1000, rounding as needed." You can scale large numbers using this technique. For example, you can use the format str
100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than im
of the decimal separator are treated simply as specifying the use of a thousand separator. (Note: In some locales, a period is used as
The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your sys
- + $ ( ) space Displays the character as is, in the position specified by the format string. To display a character other than one of those listed, prece
(\).
E-, E+, e-, or e+ If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scie
(Scientific format) is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the
e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign n
exponents.
To demonstrate custom numeric formats using combinations of the characters listed above, create a new "Try It" project, and place the following
code in Sub Main:
strUserInput = Console.ReadLine()
dblTestNumber = Val(strUserInput)
Console.ReadLine()
Run the project and
enter 1234.5. The
output will be
displayed as shown in
the screen shot on the
right.
A user-defined (custom) format expression can have from one to three sections separated by semicolons. (If the format argument contains one of
the named formats, only one section is allowed.)
The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative
values.
$#,##0;($#,##0)
If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the
following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero.
$#,##0;;\Z\e\r\o
The following table shows would be output, given the indicated format string and inputs of 5, -5, and.5, respectively.
Multiple format can be specified in the Console.WriteLine method also. The rules remain the same.
To demonstrate multiple formats using format function and Console.WriteLine method, set up another "Try It" project, and place the following code
in the main method (note: this test only uses the first three sections of the multi-format string; Null values will not be tested for):
FORMATTING DATES
Like numbers, dates can be formatted in many ways, using either Named (Pre-Defined) formats or Custom formats
The above named date/time formats for the Format function were also available in earlier versions of VB. New in .NET are the single letter
abbreviations for some of the items shown above.
"f" Displays the long date and short time according to your locale's format.
"F" Displays the long date and long time according to your locale's format.
"g" Displays the short date and short time according to your locale's format.
"M" or "m" Displays the month and the day of a date.
"R" or "r" Formats the date and time as Greenwich Mean Time (GMT)
"s" Formats the date and time as a sortable index.
"u" Formats the date and time as a GMT sortable index.
"U" Formats the date and time with the long date and long time as GMT.
"y" Formats the date as the year and month.
This next example uses the Now keyword. There are three VB keywords related to the current date and/or time:
To demonstrate the named date and time formats described above, create a new "Try It" project, and place the following code in Sub Main:
Console.WriteLine()
Console.WriteLine("Using General Date: " & Format(Now, "General Date"))
Console.WriteLine("Using Long Date: " & Format(Now, "Long Date"))
Console.WriteLine("Using Medium Date: " & Format(Now, "Medium Date"))
Console.WriteLine("Using Short Date: " & Format(Now, "Short Date"))
Console.WriteLine("Using Long Time: " & Format(Now, "Long Time"))
Console.WriteLine("Using Medium Time: " & Format(Now, "Medium Time"))
Console.WriteLine("Using Short Time: " & Format(Now, "Short Time"))
Console.WriteLine()
Console.WriteLine("Using f: " & Format(Now, "f"))
Console.WriteLine("Using F: " & Format(Now, "F"))
Console.WriteLine("Using g: " & Format(Now, "g"))
Console.WriteLine("Using M: " & Format(Now, "M"))
Console.WriteLine("Using R: " & Format(Now, "R"))
Console.WriteLine("Using s: " & Format(Now, "s"))
Console.WriteLine("Using u: " & Format(Now, "u"))
Console.WriteLine("Using U: " & Format(Now, "U"))
Console.WriteLine("Using y: " & Format(Now, "y"))
Console.ReadLine()
Run the project. The current date
and/or time, formatted in the various
ways, will be displayed:
In addition to the named date/time formats described previously, you can also create custom date/time formats using a combination of specific
characters recognized by the Format function, shown in the table below:
Character Description
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator
separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in
formatted output is determined by your system's LocaleID value.
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator
separates the day, month, and year when date values are formatted. The actual character used as the date separator in
formatted output is determined by your locale.
(%) Used to indicate that the following character should be read as a single-letter format without regard to any trailing letters.
Also used to indicate that a single-letter format is read as a user-defined format.
The need for this is because certain single-letter format specifiers are used as pre-defined formats. For example, the format
specifier "d" is used for the pre-defined "Short Date" format; however, as indicated below, the letter "d" is also used to specify
the day as a number when used in a user-defined format. So if you wanted to make a user-defined format that displays only
the day number, there would be a conflict. The use of the % character resolves that conflict.
To demonstrate custom numeric formats using combinations of the characters listed above, create a new "Try It" project, and place the following
code in Sub Main:
VB6 VB.NET
"ddddd" and "dddddd" could be used to Not supported; both behave the same as "dddd" to display the full name of the day. To display
display the short date or long date, the short date use the pre-defined format "Short Date" or "d"; for the long date use the pre-
respectively. defined format "Long Date" or "D".
"w" could be used to display the day of Not supported as a Format specifier. Instead, the DatePart function can be used as follows:
week (1 through 7) CStr(DatePart("w", DateTimeVariable))
- or -
CStr(DatePart(DateInterval.Weekday, DateTimeVariable))
"ww" could be used to display the week of Not supported as a Format specifier. Instead, the DatePart function can be used as follows:
year (1 through 53) CStr(DatePart("ww", DateTimeVariable))
- or -
CStr(DatePart(DateInterval.WeekOfYear, DateTimeVariable))
"q" could be used to display the quarter of Not supported as a Format specifier. Instead, the DatePart function can be used as follows:
the year as a number from 1 to 4 CStr(DatePart("q", DateTimeVariable))
- or -
CStr(DatePart(DateInterval.Quarter, DateTimeVariable))
Uppercase "M" or lowercase "m" could be "M" is now case-sensitive. Uppercase "M" is used for the month; lowercase "m" is used for the
used to display either the month or minute minute. "N" and "n" are not used.
("M" or "m" would be interpreted as the
minute if it immediately followed "H" or "h").
Also, uppercase "N" or lowercase "n" could
be used to display the minute.
Uppercase "H" or lowercase "h" could be "H" is now case-sensitive. Uppercase "H" represents the hour on the 24-hour clock; lowercase
used display the hour. If one of the "h" represents the hour on the 12-hour clock.
"AM/PM" specifiers was also used, the hour
would be a value between 1 and 12;
otherwise, the hour would be a value
between 0 and 23.
Various AM/PM specifiers, such "t" is used to display "A" or "P"; "tt" is used to display "AM" or "PM".
as "AM/PM", "am/pm", "A/P", "a/p", or
"AMPM." could be used to display AM or
PM (or just A or P) in upper or lower case.
FORMATTING STRINGS
In classic VB (VB6), the Format function provided options for applying custom formatting to strings, such as converting the case, padding, and
justification. In VB.NET, these options were dropped from the Format function, probably because the options provided are better handled through
standard string-handling functions. However – if you really want to – you can resurrect this functionality through the Visual Basic Compatibility
library. How to do this will be shown in the steps below.
First, let's take a look at the options that were provided. Custom string formatting could be accomplished by using the specific characters shown in
the table below:
To demonstrate custom string formats using combinations of the characters listed above, create a new "Try It" project. But before you can add the
code, you must first prepare the program to use the legacy version of the Format function. How to do this is shown in the steps below:
At this point, you can add the code. Place the following code in Sub Main. (Note that you must qualify the Format function with Support.).
Console.WriteLine()
Console.WriteLine("Using '>': " & Support.Format(strName, ">"))
Console.WriteLine("Using '<': " & Support.Format(strName, "<"))
Console.WriteLine("Using '@': " & "Hello there,
" & Support.Format(strName, "@@@@@@@@@@") & ". How are you?")
Console.WriteLine("Using '&': " & "Hello there,
" & Support.Format(strName, "&&&&&&&&&&") & ". How are you?")
Console.WriteLine("Using '!@': " & "Hello there,
" & Support.Format(strName, "!@@@@@@@@@@") & ". How are you?")
Console.WriteLine("Using '!&': " & "Hello there,
" & Support.Format(strName, "!&&&&&&&&&&") & ". How are you?")
Console.WriteLine("Using '\': " & Support.Format(strName, "\H\e\l\l\o\,\ &&&&&&&&&&\."))
Console.WriteLine("Using embedded quotes: " & Support.Format(strName, """Hello, ""&&&&&&&&&&""."""))
Console.ReadLine()
Run the project. Enter your
name when prompted, and note
the effects of the formatting
options used.