• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. Database Basics > Formatting Techniques

4.8. Formatting Techniques

Once you have query data in the form of a result set, you might want to massage it a bit before outputting it to the browser or to a file. ColdFusion provides several built-in functions for formatting a variety of datatypes. This section covers some of the more popular functions for formatting strings, HTML code, numbers, currency, dates, times, and Boolean values. For more information on all the functions covered in this section, see Appendix B.

4.8.1. Formatting Plain-Text Strings

ColdFusion provides functions for formatting text strings: ParagraphFormat( ), Ucase( ), Lcase( ), JSStringFormat( ), and XMLFormat( ). Each function is covered in the sections that follow.

4.8.1.1. Using ParagraphFormat

ParagraphFormat( ) takes a string and formats it so that single newline characters are replaced with a space, and double newline characters are replaced with HTML <P> tags. This function is most often used to display data that has been entered into a Textarea HTML form field. The following example shows how the ParagraphFormat( ) function handles single and double newline characters:

<CFSET MyText="This is my block of text.
It has both single newline characters in it like this paragraph, and double 
newline characters like in the next paragraph.

This is the paragraph with the double newline characters.">

<FORM>
<CFOUTPUT>
<TEXTAREA COLS=50 ROWS=10 NAME="TheText" WRAP="virtual">
#ParagraphFormat(MyText)#
</TEXTAREA>
</CFOUTPUT>
</FORM>

					  

4.8.1.2. Changing case

You can change the case of an entire string using the Ucase( ) and Lcase( ) functions. Ucase( ) converts a string to all uppercase characters, while Lcase( ) converts a string to all lowercase characters. The following example demonstrates both functions:

<CFSET MyString = "This Is A Mixed Case String!">

<H3>UCase/LCase</H3>
<CFOUTPUT>
Original String: #MyString#<BR>
After UCase: #UCase(MyString)#<BR>
After LCase: #LCase(MyString)#
</CFOUTPUT>

4.8.1.3. Making strings JavaScript-safe

On occasion, you may need to retrieve a string from a database for use in a JavaScript function within your application. The JSStringFormat( ) function can be used to make the string safe for use in JavaScript statements by automatically escaping special characters that normally cause a problem, such as double quotes, single quotes, and the newline character (\). The following example returns a string that has been formatted for use in a JavaScript statement:

<CFSET MyString="""Escape double quotes"". Escape the \ character. 'Escape
     single quotes'">

<CFSET SafeString=JSStringFormat(MyString)>

<CFOUTPUT>
<B>Original String:</B> #MyString#<BR>
<B>JavaScript Safe String:</B> #SafeString#
</CFOUTPUT>

4.8.1.4. Making strings safe for XML

You can make a string safe to use with XML by using the XMLFormat( ) function. XMLFormat( ) takes a string as its only parameter and returns it in a format that is safe to use with XML by escaping the following special characters:

Ampersand (&)
Double quotation mark (")
Greater than sign (>)
Less than sign (<)
Single quotation mark (')

The following example takes a string and makes it safe to use with XML:

<CFSET MyString="Here's an example of the XMLFormat function: 5+5<20">

<CFOUTPUT>
#XMLFormat(MyString)#
</CFOUTPUT>

<P>
<I>View the page source to see the escaped text.</I>

4.8.2. Formatting HTML

In order to display literal HTML or CFML code, it is necessary to escape certain special characters so that they don't cause the browser to interpret the code contained inside them. For example, if you have a string that contains Hello <B>World!</B>, and you want to display the HTML code contained in the string without having it execute, you need to escape the < and > characters. ColdFusion provides you with two functions to do this: HTMLCodeFormat( ) and HTMLEditFormat( ).

4.8.2.1. HTMLCodeFormat

The HTMLCodeFormat( ) function returns a string enclosed in <PRE> and </PRE> tags with all carriage returns removed and special characters (< > " &) escaped. The function takes two parameters, a string to format and optionally, the HTML version to use for the character escape sequences. Valid entries for the HTML version are shown in Table 4-4.

Table 4-4. HTML Versions
Value Description
-1 Current HTML version
2.0 HTML v2.0 (default)
3.2 HTML v3.0


The following example demonstrates the HTMLCodeFormat( ) function:

<CFSET MyString="<H3>This is an example of the HTMLCodeFormat function.</H3>
View the source of this document to see the escaping of the HTML characters.">

<CFOUTPUT>
#HTMLCodeFormat(MyString, "3.2")#
</CFOUTPUT>

					  

4.8.2.2. HTMLEditFormat

The HTMLEditFormat( ) function is almost identical in functionality to HTMLCodeFormat( ). The only difference is that it doesn't add <PRE></PRE> tags to the output returned by the function. The following example demonstrates the HTMLEditFormat( ) function:

<CFSET MyString="<H3>This is an example of the HTMLEditFormat function.</H3>
View the source of this document to see the escaping of the HTML characters.">

<CFOUTPUT>
#HTMLEditFormat(MyString, "3.2")#
</CFOUTPUT>

					  

4.8.3. Formatting Numbers

ColdFusion provides three functions for formatting numbers: DecimalFormat( ), NumberFormat( ), and LSNumberFormat( ). These functions can format numbers in a variety of ways, as described in the following sections.

4.8.3.1. Formatting decimal numbers

The DecimalFormat( ) function takes a number and returns it formatted to two decimal places, with thousands separators. The following example formats a variety of numbers using DecimalFormat( ):

<CFOUTPUT>
1:  #DecimalFormat(1)#<BR>
10: #DecimalFormat(10)#<BR>
100: #DecimalFormat(100)#<BR>
1000: #DecimalFormat(1000)#<BR>
10000: #DecimalFormat(10000)#<BR>
100000: #DecimalFormat(100000)#<BR>
1000000: #DecimalFormat(1000000)#<BR>
</CFOUTPUT> 

4.8.3.2. General number formatting

The NumberFormat( ) function handles general number formatting in ColdFusion. NumberFormat( ) allows you to format numbers using a variety of masks. The function accepts two parameters, the number you wish to format and a mask to specify the formatting, in the form NumberFormat(Number, 'mask'). If no mask is supplied, NumberFormat( ) returns the number formatted with thousands separators. Valid entries for the mask are listed in Table 4-5.

Table 4-5. Mask Values for NumberFormat( )
Mask Description
- Optional digit placeholder
9 Optional digit placeholder; same as _ but better for showing decimal places
. Decimal point location
0 Forces padding with zeros
( ) Surrounds negative numbers in parentheses
+ Places a plus sign in front of positive numbers and a minus sign in front of negative numbers
- Places a space in front of positive numbers and a minus sign in front of negative numbers
, Separates thousands with commas
L Left justifies the number within the width of the mask
C Centers the number within the width of the mask
$ Places a dollar sign in front of the number
^ Separates left from right formatting


The following example shows the NumberFormat( ) function applied to various numbers:

<!--- Assign a number to a variable to be used throughout the example --->
<CFSET MyNumber = 1000.99>

<H3>Formatting Numeric Values using NumberFormat</H3>

<CFOUTPUT>
<B>MyNumber = #MyNumber#</B>
<P>
NumberFormat(MyNumber, '____'): #NumberFormat(MyNumber, '____')#<BR>
NumberFormat(MyNumber, '9999.99'): #NumberFormat(MyNumber, '9999.99')#<BR>
NumberFormat(MyNumber, '09999.9900'): #NumberFormat(MyNumber, '09999.9900')#<BR>
NumberFormat(-MyNumber, '(9999.99)'): #NumberFormat(-MyNumber, '(9999.99)')#<BR>
NumberFormat(MyNumber, '+9999.99'): #NumberFormat(MyNumber, '+9999.99')#<BR>
NumberFormat(-MyNumber, '+9999.99'): #NumberFormat(-MyNumber, '+9999.99')#<BR>
NumberFormat(MyNumber, '-9999.99'): #NumberFormat(MyNumber, '-9999.99')#<BR>
NumberFormat(-MyNumber, '-9999.99'): #NumberFormat(-MyNumber, '-9999.99')#<BR>
NumberFormat(MyNumber, '$9,999.99'): #NumberFormat(MyNumber, '$9,999.99')#<BR>
NumberFormat(MyNumber, 'L999,999.99'): #NumberFormat(MyNumber, 'L999,999.99')#<BR>
NumberFormat(MyNumber, 'C999,999.99'): #NumberFormat(MyNumber, 'C999,999.99')#<BR>
NumberFormat(MyNumber, 'C_____(^___)'): #NumberFormat(MyNumber, 'C_____(^___)')#
</CFOUTPUT>

					  

4.8.3.3. Locale-specific number formatting

In addition to general number formatting using the NumberFormat( ) function, ColdFusion provides another function for formatting numbers in a format that is locale-specific. Locale-specific formatting allows you to format numbers for a specific language or dialect (often country-specific). For example, in many European countries, the period (.) is used as a thousands separator instead of the comma (,) as in the United States. The LSNumberFormat( ) function behaves the same as the NumberFormat( ) function (using the same masks), but it takes into account the formatting used by the default locale. If no formatting mask is supplied, LSNumberFormat( ) returns the number as an integer.

The following example loops through each locale supported by ColdFusion and applies a variety of different number masks for each locale:

<H3>Formatting Locale Specific Numeric Values using LSNumberFormat</H3>

<!--- loop over each locale.  The list of locales is obtained from the server 
      variable Server.ColdFusion.SupportedLocales --->
<CFLOOP INDEX="locale" LIST="#Server.Coldfusion.SupportedLocales#">
<!--- this causes the CF server to assume the locale specified by the current 
      iteration of the loop --->
<CFSET temp = SetLocale(locale)>

<CFOUTPUT>
<P>
<B>#locale#</B><BR>
LSNumberFormat(1000.99, '____'): #LSNumberFormat(1000.99, '____')#<BR>
LSNumberFormat(1000.99, '9999.99'): #LSNumberFormat(1000.99, '9999.99')#<BR>
LSNumberFormat(1000.99, '09999.9900'): #LSNumberFormat(1000.99, '09999.9900')#<BR>
LSNumberFormat(-1000.99, '(9999.99)'): #LSNumberFormat(-1000.99, '(9999.99)')#<BR>
LSNumberFormat(1000.99, '+9999.99'): #LSNumberFormat(1000.99, '+9999.99')#<BR>
LSNumberFormat(-1000.99, '+9999.99'): #LSNumberFormat(-1000.99, '+9999.99')#<BR>
LSNumberFormat(1000.99, '-9999.99'): #LSNumberFormat(1000.99, '-9999.99')#<BR>
LSNumberFormat(-1000.99, '-9999.99'): #LSNumberFormat(-1000.99, '-9999.99')#<BR>
LSNumberFormat(1000.99, '$9,999.99'): #LSNumberFormat(1000.99, '$9,999.99')#<BR>
LSNumberFormat(1000.99, 'L999,999.99'): #LSNumberFormat(1000.99, 'L999,999.99')#<BR>
LSNumberFormat(1000.99, 'C999,999.99'): #LSNumberFormat(1000.99,'C999,999.99')#<BR>
LSNumberFormat(1000.99, 'C____(^___)'): #LSNumberFormat(1000.99, 'C____(^___)')#<BR>
</CFOUTPUT>
</CFLOOP>


					  

4.8.4. Formatting Currency Values

Numeric values can be automatically formatted as currency values with the help of three ColdFusion functions: DollarFormat( ), LSCurrencyFormat( ), and LSEuroCurrencyFormat( ).

4.8.4.1. Formatting dollars

The DollarFormat( ) function returns a number formatted as U.S. dollars. The returned number is formatted to two decimal places with a dollar sign and thousands separators. If the number is negative, it is returned in parentheses. The following example formats a variety of numbers using DollarFormat( ):

<CFOUTPUT>
-1000: #DollarFormat(-1000)#<BR>
-100: #DollarFormat(-100)#<BR>
-10: #DollarFormat(-10)#<BR>
-1: #DollarFormat(-1)#<BR>
1:  #DollarFormat(1)#<BR>
10: #DollarFormat(10)#<BR>
100: #DollarFormat(100)#<BR>
1000: #DollarFormat(1000)#<BR>
10000: #DollarFormat(10000)#<BR>
100000: #DollarFormat(100000)#<BR>
1000000: #DollarFormat(1000000)#<BR>
</CFOUTPUT>

4.8.4.2. Locale-specific currency formatting

In addition to U.S. dollar formatting using the DollarFormat function, ColdFusion provides another function for formatting currency values specific to a particular locale. The LSCurrencyFormat( ) function behaves the same as the DollarFormat( ) function, but it takes into account the currency conventions used by the default locale. The function takes two parameters, a numeric value and an optional locale-specific convention. Table 4-6 lists the valid values for the convention.

Table 4-6. Locale-Specific Conventions for LSCurrencyFormat( )
Value Description
None Returns the amount
Local Returns the currency amount with locale-specific currency formatting; the default
International Returns the currency value with its corresponding three-letter international currency prefix


The following example loops through each locale supported by ColdFusion and applies each type of currency mask to a currency value for each locale:

<H3>Formatting Locale Specific Currency Values using LSCurrencyFormat</H3>

<!--- loop over each locale.  The list of locales is obtained from the server 
      variable Server.ColdFusion.SupportedLocales --->
<CFLOOP INDEX="locale" LIST="#Server.Coldfusion.SupportedLocales#">
<!--- this causes the CF server to assume the locale specified by the current 
      iteration of the loop --->
<CFSET temp = SetLocale(locale)>

<CFOUTPUT>
<P>
<B>#locale#</B><BR>
None: #LSCurrencyFormat(1000000.99, "None")#<BR>
Local: #LSCurrencyFormat(1000000.99, "Local")#<BR>
International: #LSCurrencyFormat(1000000.99, "International")#<BR>
</CFOUTPUT>
</CFLOOP>

					  

4.8.4.3. Locale-specific currency formatting with the Euro

The final currency formatting function, LSEuroCurrencyFormat( ), is the same as the LSCurrencyFormat( ) function except it returns the formatted currency with the Euro symbol. The following example displays Euro currency formats for each locale:

<H3>Formatting Locale Specific Currency Values with the Euro using 
    LSCurrencyFormat</H3>

<!--- loop over each locale.  The list of locales is obtained from the server 
      variable Server.ColdFusion.SupportedLocales --->
<CFLOOP INDEX="locale" LIST="#Server.Coldfusion.SupportedLocales#">
<!--- this causes the CF server to assume the locale specified by the current 
      iteration of the loop --->
<CFSET temp = SetLocale(locale)>

<CFOUTPUT>
<P>
<B>#locale#</B><BR>
None: #LSEuroCurrencyFormat(1000000.99, "None")#<BR>
Local: #LSEuroCurrencyFormat(1000000.99, "Local")#<BR>
International: #LSEuroCurrencyFormat(1000000.99, "International")#<BR>
</CFOUTPUT>
</CFLOOP>


					  

4.8.5. Formatting Boolean Values

ColdFusion uses the Boolean datatype to store the value generated by a logical operation. Boolean values are stored as either TRUE or FALSE. In numeric operations, Boolean values evaluate to 1 for TRUE and 0 for FALSE. When dealing with strings, Boolean values are set to Yes for TRUE and No for FALSE. Because most users are used to seeing the results of a Boolean operation as either Yes or No, ColdFusion has a function called YesNoFormat( ) you can use to automatically convert any Boolean value to its equivalent Yes/No format (all non-zero values are returned as Yes, while a zero value is returned as No). The following example demonstrates this by applying the YesNoFormat( ) function to a variety of Boolean values:

<H3>Formatting Boolean Values using YesNoFormat</H3>

<CFOUTPUT>
-1: #YesNoFormat(-1)#<BR>
-1.123: #YesNoFormat(-1.123)#<BR>
-0.123: #YesNoFormat(-0.123)#<BR>
0: #YesNoFormat(0)#<BR>
0.123: #YesNoFormat(0.123)#<BR>
1: #YesNoFormat(1)#<BR>
1.123: #YesNoFormat(1.123)#
</CFOUTPUT>

Please note that Version 4.01 of ColdFusion contains a bug in the YesNoFormat( ) function that causes certain negative decimal values to evaluate incorrectly. This behavior was fixed in ColdFusion 4.5.

4.8.6. Formatting Dates and Times

Depending on the database you use, date and time values returned as part of a query result set can come in a variety of formats. ColdFusion affords a lot of flexibility in formatting date and time values before you output them to the browser.

4.8.6.1. General date formatting

General date formatting is handled by the DateFormat( ) function. DateFormat( ) allows you to format dates using a variety of masks.[4] The function accepts two parameters, the date you wish to format and a mask to specify the formatting in the format DateFormat(date, "mask"). If no mask is supplied, DateFormat( ) defaults to dd-mmm-yy. Valid entries for the date mask are shown in Table 4-7.

[4] If you are running ColdFusion on Unix and have Fast Date/Time Parsing enabled in the Server area of the ColdFusion Administrator, you must refer to date objects as month, day, year. When using the DateFormat( ) function, a date mask following the required format (month, day, year) must be used to parse the date object.

Table 4-7. Mask Values for DateFormat( )
Mask Description
d Day of the month as a number with no leading zero for single-digit days
dd Day of the month as a number with a leading zero for single-digit days
ddd Three-letter abbreviation for day of the week
dddd Full name of the day of the week
gg

Period/era; this mask is currently ignored
m Month as a number with no leading zero for single-digit months
mm Month as a number with a leading zero for single-digit months
mmm Three-letter abbreviation for the month
mmmm Full name of the month
y Last two digits of year with no leading zero for years less than 10
yy Last two digits of year with a leading zero for years less than 10
yyyy Four-digit year


You should note that DateFormat( ) supports U.S. date formats only. To use locale-specific date formats, see the LSDateFormat( ) function in the next section.

The following example demonstrates the DateFormat( ) function utilizing a variety of different date masks:

<!--- set TheDate to the current date --->
<CFSET TheDate = Now(  )>

<H3>Formatting US Date Values using DateFormat</H3>

<CFOUTPUT>
TheDate = #DateFormat(TheDate, "mm/dd/yyyy")#
<P>
DateFormat(TheDate, "m/d/yy"): #DateFormat(TheDate, "m/d/yy")#<BR>
DateFormat(TheDate, "mm/dd/yy"): #DateFormat(TheDate, "mm/dd/yy")#<BR>
DateFormat(TheDate, "mm/dd/yyyy"): #DateFormat(TheDate, "mm/dd/yyyy")#<BR>
DateFormat(TheDate, "dd/mm/yyyy"): #DateFormat(TheDate, "dd/mm/yyyy")#<BR>
DateFormat(TheDate, "dd mmm yy"): #DateFormat(TheDate, "dd mmm yy")#<BR>
DateFormat(TheDate, "dddd mmmm dd, yyyy"): #DateFormat(TheDate, "dddd mmmm dd
     Yyyy")#<BR>
</CFOUTPUT>

					  

4.8.6.2. Locale-specific date formatting

In addition to U.S. date formatting using the DateFormat( ) function, ColdFusion provides another function for formatting dates specific to a particular locale. The LSDateFormat( ) function behaves the same as the DateFormat( ) function, but it takes into account the formatting used by the default locale. If no formatting mask is supplied, LSDateFormat( ) uses the locale-specific default.

The following example loops through each locale supported by ColdFusion and applies a number of different date masks to the current date for each locale:

<H3>Formatting Locale Specific Date Values using LSDateFormat</H3>

<!--- loop over each locale.  The list of locales is obtained from the server 
      variable Server.ColdFusion.SupportedLocales --->
<CFLOOP INDEX="locale" LIST="#Server.Coldfusion.SupportedLocales#">
<!--- this causes the CF server to assume the locale specified by the current 
      iteration of the loop --->
<CFSET temp = SetLocale(locale)>

<!--- output formatted dates using a variety of masks --->
<CFOUTPUT>
<P>
<B>#locale#</B><BR>
#LSDateFormat(Now(  ))#<BR> 
#LSDateFormat(Now(  ), "d/m/yy")#<BR>
#LSDateFormat(Now(  ), "d-mmm-yyyy")#<BR>
#LSDateFormat(Now(  ), "dd mmm yy")#<BR>
#LSDateFormat(Now(  ), "dddd, mmmm dd, yyyy")#<BR>
#LSDateFormat(Now(  ), "mm/dd/yyyy")#<BR>
#LSDateFormat(Now(  ), "mmmm d, yyyy")#<BR>
#LSDateFormat(Now(  ), "mmm-dd-yyyy")#<BR>
</CFOUTPUT>
</CFLOOP>

					  

4.8.6.3. Time formatting

You can format times in ColdFusion using the TimeFormat( ) function. TimeFormat( ) is similar to the DateFormat( ) function in that it allows you to use a mask to control the formatting. The function accepts two parameters, the time you wish to format and a mask to specify the formatting in the format TimeFormat(time, "mask"). If no mask is specified, the default hh:mm tt is used. Valid mask values are shown in Table 4-8.

Table 4-8. Mask Values for TimeFormat( )
Mask Description
h Hours based on a 12-hour clock with no leading zeros for single-digit hours
hh Hours based on a 12-hour clock with leading zeros for single-digit hours
H Hours based on a 24-hour clock with no leading zeros for single-digit hours
HH Hours based on a 24-hour clock with leading zeros for single-digit hours
m Minutes with no leading zero for single-digit minutes
mm Minutes with a leading zero for single-digit minutes
s Seconds with no leading zero for single-digit seconds
ss Seconds with a leading zero for single-digit seconds
t Single character meridian, either A or P
tt Multicharacter meridian, either AM or PM


The following example demonstrates the TimeFormat( ) function using a number of time masks:

<!--- set a variable containing the current time using the Now function --->
<CFSET TheTime = Now(  )>

<H3>Formatting Time Values using TimeFormat</H3>

<CFOUTPUT>
TheTime = #TimeFormat(TheTime,"hh:mm:ss tt")#
<P>
TimeFormat(TheTime, "h:m:s"): #TimeFormat(TheTime, "h:m:s")#<BR>
TimeFormat(TheTime, "h:m:s t"): #TimeFormat(TheTime, "h:m:s t")#<BR>
TimeFormat(TheTime, "hh:mm:ss"): #TimeFormat(TheTime, "hh:mm:ss")#<BR>
TimeFormat(TheTime, "hh:mm:ss tt"): #TimeFormat(TheTime, "hh:mm:ss tt")#<BR>
TimeFormat(TheTime, "H:M:ss"): #TimeFormat(TheTime, "H:M:s")#<BR>
TimeFormat(TheTime, "HH:MM:ss"): #TimeFormat(TheTime, "HH:MM:ss")#<BR>
</CFOUTPUT>

					  

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint