Accessibility
 
 

Data Type Conversion

ColdFusion automatically converts between data types to satisfy the requirements of an expression's operations, including a function's argument requirements. As a result, you generally don't have to be concerned about compatibility between data types and the conversions from one data type to another.

Operation-Driven Evaluation

Conventional programming languages enforce strict rules about mixing objects of different types in expressions. For example, in a language such as C++ or Basic, the expression ("8" * 10) produces an error because the multiplication operator requires two numerical operands and "8" is a string. When you program in such languages you must convert between data types to ensure error-free program execution. For example, the previous expression might have to be written as (ToNumber("8") * 10).

In ColdFusion, however, the expression ("8" * 10) evaluates to the number 80 without generating an error. When ColdFusion processes the multiplication operator, it automatically attempts to convert its operands to numbers. Since "8" can be successfully converted to the number 8, the expression evaluates to 80. ColdFusion processes expressions and functions in this sequence:

  1. For each operator in an expression, it determines the required operands. For example, the multiplication operator requires numeric operands and the CONTAINS operator requires string operands.
  2. For functions, it determines the type required for each function argument. For example, the Min function requires two numbers as arguments and the Len function requires a string.
  3. It evaluates all operands or function arguments.
  4. It converts all operands or arguments whose types differ from the required type. If a conversion fails, it reports an error.

Conversion Between Types

Although the expression evaluation mechanism in ColdFusion is very powerful, it cannot automatically convert all data. For example, "eight" * 10 produces an error because ColdFusion cannot convert the string "eight" to the number 8. Therefore, you must understand the rules for conversion between data types.

The following table explains how conversions are performed. The first column shows values to convert. The last four columns show the result of conversion to the listed data type.

Value As Boolean As number As date-time As string
"Yes" TRUE 1 Error "Yes"
"No" FALSE 0 Error "No"
TRUE TRUE 1 Error "Yes"
FALSE FALSE 0 Error "No"
Number TRUE if Number is not 0, FALSE otherwise. Number See Date-Time Values Number is converted using a default format.
String If "Yes" or "No" or if the string can be converted to a number, it is treated as above. If it represents a number (for example, "1,000" or "12.36E-12"), it is converted to the corresponding number. If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. If it is an ODBC date, time, or timestamp (for example "{ts '2001-06-14 11:30:13'} "; or if it is expressed in a standard US date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value.

Days of week or unusual punctuation result in error.

Dashes, forward-slashes, and spaces are generally allowed.
String
Date Error The numeric value of the date-time object. Date An ODBC timestamp.

Complex types, such as arrays, queries, and COM objects, cannot be converted.

Type conversion notes

The following sections detail specific rules and considerations for converting between types.

Case insensitivity and Boolean conversion

Because ColdFusion expression evaluation is not case sensitive, Yes, YES, and yes are equivalent; False, FALSE, and false are equivalent; No, NO, and no are equivalent; and True, TRUE, and true are equivalent.

Converting binary data

ColdFusion cannot automatically convert binary data to other data types. To convert binary data use the ToBase64 and ToString functions. For more information, see Binary Data Type and Base64 Encoding.

Converting date and time data

To ensure that a date and time value is expressed as a real number, add 0 to the variable. The following example illustrates this use:

<cfset mynow = now()>
<cfoutput>#mynow#</cfoutput>
<cfset mynow = mynow + 0> <cfoutput>#mynow#</cfoutput>

At 1:45 PM on July 7, 2001, its output looked like this:

{ts '2001-07-06 13:45:30'}
37078.5732639

Converting numeric values

When ColdFusion evaluates an expression that includes both integers and real numbers, the result is a real number. To convert a real number to an integer, use a ColdFusion function. The Int, Round, Fix, and Ceiling functions convert real numbers to integers and differ in their treatment of the fractional part of the number.

If you use a hidden form field with a name that has the suffix _integer or _range to validate a form input field, ColdFusion truncates real numbers entered into the field and passes the resulting integer to the action page.

If you use a hidden form field with a name that has the suffix _integer, _float, or _range to validate a form input field, and the entered data contains a dollar amount (including a dollar sign) or a numeric value with commas, ColdFusion considers the input to be valid, removes the dollar sign or commas from the value, and passes the resulting integer or real number to the action page.

Evaluation and type conversion issues

This section explains several issues that you might encounter with type evaluation and conversion.

Comparing variables to TRUE or FALSE

You might expect the following two cfif tags to produce the same results:

<cfif myVariable>
<cfoutput>myVariable equals #myVariable# and is TRUE 

</cfoutput>
</cfif>
<cfif myVariable IS TRUE>
<cfoutput>myVariable equals #myVariable# and is TRUE 
</cfoutput>
</cfif>

However, if myVariable has a numeric value such as 12, only the first example produces a result. In the second case, the value of myVariable is not converted to a Boolean data type, because the IS operator does not require a specific data type and just tests the two values for identity. Therefore, ColdFusion compares the value 12 with the constant TRUE. The two are not equal, so nothing is printed. If myVariable is 1, "Yes", or True, however, both examples print the same result, because ColdFusion considers these to be identical to Boolean TRUE.

If you use

<cfif myVariable IS NOT FALSE>
<cfoutput>myVariable equals #myVariable# and IS NOT FALSE
</cfoutput>
</cfif>

The output statement does display because the contents of the variable, 12, is not equal to the Boolean constant FALSE.

Ambiguous type expressions and strings

When ColdFusion evaluates an expression that does not require strings, including all comparison operations such as IS or GT, it checks whether it can convert each string value to a number or date-time object. If so, ColdFusion converts it to the corresponding number or date-time value (which is stored as a number). It then uses the number in the expression.

With short strings such as 1a and 2P, this behavior can produce unexpected results. ColdFusion can interpret a single "A" as AM and a single "P" as PM. This can cause ColdFusion to interpret strings that are not so intended, as times as date-time values.

Similarly, if the strings can be interpreted as numbers, you can get unexpected results.

For example, ColdFusion interprets the following expressions as shown:

Expression Interpreted as
<cfif "1a" EQ "01:00"> If 1:00am is 1:00am
<cfif "1P" GT "2A"> If 1:00pm is later than 2:00am
<cfset age="4a">
<cfset age=age + 7>
Treat the variable age as 4:00 am, convert it to the date-time
value 0.16666666667, and 7 to make 7.16666666667.
<cfif "0.0" IS "0"> If 0 is 0

To prevent such ambiguities when you compare strings, use the ColdFusion string comparison functions Compare and CompareNoCase instead of the comparison operators.

You can also use the IsDate() function to determine whether a string can be interpreted as a date-time value, or to add characters to a string before comparison to avoid incorrect interpretation.

Date-time functions and queries when ODBC is not supported

ColdFusion creates Open Database Connectivity (ODBC) timestamp values when it converts date-time objects, such as the results returned by the ColdFusion Now, CreateDate, CreateTime, and CreateDateTime functions, to strings. As a result, you can get unexpected results when using dates with a database driver that does not support ODBC escape sequences or when you are using SQL in a query of queries.

If you use SQL to insert data into a database or in a WHERE clause to select data from a database, and the database driver does not support ODBC-formatted dates, use the DateFormat function to convert the date-time value to a valid format for the driver. This rule also applies to queries of queries.

For example, the following SQL statement uses the DateFormat function in a query of queries to select rows that have MyDate values in the future:

<cfquery name="MyQofQQ" dbtype="query">
SELECT * 
FROM DateQuery
WHERE MyDate >= '#DateFormat(Now())#'
</cfquery>

The following query of queries fails with the error message "Error: {ts is not a valid date," because ColdFusion Now function returns an ODBC timestamp:

<cfquery name="MyQofQQ" dbtype="query">
SELECT * 
FROM DateQuery
WHERE MyDate >= '#now()#'
</cfquery>

Using JavaCast with overloaded Java methods

You can overload Java methods so a class can have several identically named methods that differ only in parameter data types. At runtime, the VM attempts to resolve the specific method to use, based on the types of the parameters passed in the call. Because ColdFusion does not use explicit types, you cannot predict which version of the method the JVM will use.

The ColdFusion JavaCast function helps you ensure that the right method executes by specifying the Java type of a variable, as in the following code:

<cfset  emp.SetJobGrade(JavaCast("int", JobGrade)>

The JavaCast function takes two parameters: a string representing the Java data type and the variable whose type you are setting. You can specify the following Java data types: bool, int, long, float, double, and String.

For more information on the JavaCast function, see CFML Reference.

The effect of quotes

To ensure that ColdFusion properly interprets string data, surround strings in single or double quotes. For example, ColdFusion evaluates "10/2/2001" as a string that can be converted into a date-time object. However, it evaluates 10/2/2001 as a mathematical expression 5/2001, which evaluates to 0.00249875062469.

Examples of Type Conversion in Expression Evaluation

The following examples demonstrate ColdFusion expression evaluation.

Example 1
2 * TRUE + "YES" - ('y' & "es")
Result value as string: "2"
Explanation: (2*TRUE) is equal to 2; ("YES"-"yes") is equal to 0; 2 + 0 equals 2.

Example 2
TRUE AND 2 * 3
Result value as string: "YES"
Explanation: 6 is converted to Boolean TRUE; TRUE AND TRUE is TRUE.

Example 3
"Five is " & 5
Result value as string: "Five is 5"
Explanation: 5 is converted to the string "5".

Example 4
DateFormat("October 30, 2001" + 1)
Result value as string: "31-Oct-01"
Explanation: The addition operator forces the string "October 30, 2001" to be converted to a date-time object and then to a number. The number is incremented by one. The DateFormat function requires its argument to be a date-time object; thus the result of the addition is converted to a date-and-time object. 1 is added to the date-time object, moving it ahead by one day to October 31, 2001.

Scopes

Variables differ in the source of the data, the places in your code where they are meaningful, and how long their values persist. These considerations are generally referred to as a variable's scope.

Scope Types

The following table lists the types of ColdFusion scopes and describes their uses. For more information on the function of each scope type, see Developing ColdFusion Applications.

Scope Description
Variables (local) The default scope for variables of any type that are created with the cfset and cfparam tags. A local variable is available only on the page on which it is created and any included pages (but see also the Caller scope).
Form Contains variables passed from a Form page to its action page as the result of submitting the form. (If you use the HTML form tag, you must use method="post")
URL Contains parameters passed to the current page in the URL that is used to call it. The parameters are appended to the URL in the format ?variablename = value[&variablename=value...]; for example www.MyCompany.com/ inputpage.cfm?productCode=A12CD1510&quantity=3
Attributes Used only in custom tag pages. Contains the values passed by the calling page in the custom tag's attributes.
Caller Used only in custom tag pages. The custom tag's Caller scope is a reference to the calling page's Variables scope. Any variables that you create or change in the custom tag page using the Caller scope are visible in the calling page's Variables scope.
Request Used to hold data that must be available for the duration of one HTTP request. The request scope is available to all pages, including custom tags and nested custom tags, that are processed in response to the request. This scope, which is represented as a structure, is useful for nested (child/parent) tags.

This scope can often be used in place of the Application scope, to avoid the need for locking variables.
CGI Contains environment variables identifying the context in which a page was requested. The variables available depend on the browser and server software. For a list of the commonly used CGI variables, see CFML Reference.
Cookie Contains variables maintained in a user's browser as cookies. Cookies are typically stored in a file on the browser, so they are available across browser sessions and applications. You can create memory-only Cookie variables, which are not available after the user closes the browser.
Client Contains variables that are associated with one client. Client variables let you maintain state as a user moves from page to page in an application and are available across browser sessions. By default, they are stored in the system registry, but you can store them in a cookie or a database.
Session Contains variables that are associated with one client and persist only as long as the client maintains a session. They are stored in the server's memory and can be set to time-out after a period of inactivity. You cannot use Session variables on server clusters where more than one computers can process requests from a single session.
Application Contains variables that are associated with one named application on a server. The cfapplication tag name attribute specifies the application name.
Server Contains variables that are associated with the current ColdFusion server. This scope lets you define variables that are available to all your ColdFusion pages, across multiple applications.
function local Contains variables that are declared in a custom function and exist only while the function executes.


Caution: You must lock all code that uses Session, Application, or Server scope variables. For more information on locking, see the chapter "Using the Application Framework" in Developing ColdFusion Applications.

Creating and Using Scope Variables

The following table shows how you create and refer to variables in different scopes in your code. For more information on the mechanisms for creating variables in most scopes see Creating Variables.

Scope prefix (type) Prefix required to reference Where available Created by
Variables (Local) No On the current page. Cannot be accessed by a form's action page (unless the form page is also the action page). Variables in this scope on a page that calls a custom tag can be accessed in the custom tag by using its Caller scope, but are not available to any nested custom tags. Specifying the prefix Variables, or using no prefix, when you create the variable.
Form No On the action page of a form and in custom tags called by the action page; cannot be used on a form page that is not also the action page. A form or cfform tag. Contains the values of form field tags (such as input) in the form body when the form is submitted. The variable name is the name of the form field.
URL No On the target page of the URL. The system. Contains the parameters passed in the URL query string used to access the page.
Attributes Yes On the custom tag page. The calling page passing the values to a custom tag page in the custom tag's attributes.
Caller On the custom tag page, Yes. On the calling page, No (Variables prefix is optional). On the custom tag page, by using the Caller scope prefix. On the page that calls the custom tag, as local variables (Variables scope). On the custom tag page, by specifying the prefix Caller when you create the variable.On the calling page, by specifying the prefix Variables, or using no prefix, when you create the variable.
Request Yes On the creating page and in any pages invoked during the current HTTP request after the variable is created, including in custom tags and nested custom tags. Specifying the prefix Request when you create the variable.
CGI No On any page. Values are specific to the latest browser request. The Web server. Contains the server environment variables that result from the browser request.
Cookie No For one client in one or more applications and pages, over multiple browser sessions. A cfcookie tag. You can also set memory-only cookies by specifying the prefix Cookie when you create the variable.
Client No For one client in one application, over multiple browser sessions. Specifying the prefix Client when you create the variable.
Session Yes For one client in one application and one browser session. Surround all code that uses Session variables in cflock blocks. Specifying the prefix Session when you create the variable.
Application Yes For multiple clients in one application over multiple browser sessions. Surround all code that uses Application variables in cflock blocks. Specifying the prefix Application when you create the variable.
Server Yes To any page on the ColdFusion server. Surround all code that uses Server variables in cflock blocks. Specifying the prefix Server when you create the variable.
(Function local, no prefix) Prohibited Within the body of a custom function, only while the function executes. A var statement in the function body.

Using Scopes

The following sections provide details on how you can create and use variables in different scopes.

Evaluating unscoped variables

If you use a variable name without a scope prefix, ColdFusion checks the scopes in the following order to find the variable.

  1. Variables (local scope)
  2. CGI
  3. URL
  4. Form
  5. Cookie
  6. Client

Because ColdFusion must search for variables when you do not specify the scope, you can improve performance by specifying the scope for all variables. ColdFusion releases through 5.0 have some limitations on using the Variables scope identifier, as described in the following section.

To access variables in the Attribute, Request, Session, Application, and Server scopes, you must use the scope identifier prefix.

Limitations on using scope names

The use of the scope identifiers is limited, as follows.

Using the Variables identifier with queries and structures

If you do not specify the Variables prefix when you create a query or structure, you cannot use the prefix when you reference the query object or structure.

If you do specify the Variables prefix when you create the query or structure, you must always use the prefix when you reference the query or structure.

For example, if you use the following cfquery code, you must always refer to the query variable as myQuery, not as Variables.myQuery.

<cfquery name="myquery" datasource="CompanyInfo">

Similarly, if you use the following cfquery code, you must always refer to the query variable as Variables.myQuery, not as myQuery.

<cfquery name="Variables.myquery" datasource="CompanyInfo">

The following two scripts correctly create and use structures:

<cfscript> st1 = structnew(); st1.key0 = "foo";</cfscript>

<cfscript> Variables.st1 = structnew(); Variables.st1.key0 = "foo";</ cfscript>

The following script does not work as expected:

<cfscript> st1 = structnew(); Variables.st1.key0 = "foo";</cfscript>

The script appears to create a new structure, st1 and populate its element, st1.key0. In fact, it creates an empty structure st1 and a separate simple string variable Variables.st1.key0. The following code illustrates this behavior:

<cfscript> 
	st1 = structnew(); 
	Variables.st1.key0 = "foo";
	st1.key0 = "bar"
</cfscript>
<cfoutput>
	Variables.st1.key0: #Variables.st1.key0#
st1.key0: #st1.key0#
</cfoutput>

Scopes and CFX tags

ColdFusion scopes do not apply to CFX tags. The ColdFusion page that calls a CFX tag must use tag attributes to pass data to the CFX tag. The CFX tag must use the Java Request and Response interfaces or the C++ Request class to get and return data.

The Java setVariable Response interface method and C++ CCFX::SetVariable method to return data to the Variables scope of the calling page. Therefore, they are equivalent to setting a Caller scope variable in a custom ColdFusion tag.

Scopes available as structures

ColdFusion makes the following scopes available as structures:

  • Form
  • URL
  • Attributes
  • Request
  • CGI
  • Cookie
  • Session
  • Application

You can reference the variables in these scopes as elements of a structure. To do so, specify the scope name as the structure name and the variable name as the key.


Note: Do not use the StructClear function to clear session and application variables. This can cause the loss of SessionID, CFID, CFTOKEN, and application variables. To prevent this loss, store session data in session.foo.* and then clear session.foo, and store application data in application.foo.* and then clear application.foo.

Click here to return to the previous page.