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 need to be concerned about compatibility between data types and the conversions from one data type to another. However, understanding how ColdFusion evaluates data values and converts data between types can help you prevent errors and create code more effectively.

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 numeric 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 the following 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.)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.)

  2. It evaluates all operands or function arguments.

  3. 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 powerful, it cannot automatically convert all data. For example, the expression "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 remaining 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" earlier in this chapter.

String representation of the number (for example, "8").

String

If "Yes", TrueIf "No", FalseIf it can be converted to 0, FalseIf it can be converted to any other number, True

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 U.S. date or time format, including the use of full
or abbreviated month names, it is converted to the corresponding
date-time value. Days of the week or unusual punctuation result in an error. Dashes, forward-slashes, and spaces are generally allowed.

String

Date

Error

The numeric value of the date-time object.

Date

An ODBC timestamp.

ColdFusion cannot convert complex types, such as arrays, queries, and COM objects, to other types. However, it can convert simple data elements of complex types to other simple data types.

Type conversion considerations

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

The cfoutput tag

The cfoutput tag always displays data as a string. As a result, when you display a variable using the cfoutput tag, ColdFusion applies the type conversion rules to any non-string data before displaying it. For example, the cfoutput tag displays a date-time value as an ODBC timestamp.

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 binary encoding.

Converting date and time data

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

Use cfoutput to display the result of the now function:<br>
<cfoutput>#mynow#</cfoutput><br>
Now add 0 to the result and display it again:<br>
<cfset mynow = mynow + 0>
<cfoutput>#mynow#</cfoutput>

At 1:06 PM on June 6, 2003, its output looked like this:

{ts '2003-06-03 13:06:44'}
Now add 0 to the result and display it again:
37775.5463426

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 IntRoundFix, 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.
ColdFusion does not have an inherent data type for arbitrary precision decimal numbers (BigDecimal numbers). ColdFusion initially saves such numbers as strings, and if you use them in an expression, converts the value to a numeric type, often losing precision. You can retain precision by using the PrecisionEvaluate method, which evaluates string expressions using BigDecimal precision arithmetic and can return the result as a long string of numbers. For more information, see PrecisionEvaluate in the CFML Reference.

Evaluation and type conversion issues

The following sections explain several issues that you can encounter with type evaluation and conversion.

Comparing variables to True or False

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

<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 the following code, the output statement does display, because the value of the variable, 12, is not equal to the Boolean value False:

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

As a result, use the test <cfif }}testvariable{{>, and not use the IS comparison operator when testing whether a variable is True or False. This issue is a case of the more general problem of ambiguous type expression evaluation, described in the following section.

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.
Short strings, such as 1a and 2P, 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 as date-time values in cases where this was not intended. 
Similarly, if the strings can be interpreted as numbers, you can get unexpected results.
For example, ColdFusion interprets the following expressions as shown:

Expression

Interpretation

<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 add 7 to make it 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

Many CFML functions, including the NowCreateDateCreateTime, and CreateDateTime functions, return date-time objects. ColdFusion creates Open Database Connectivity (ODBC) timestamp values when it converts date-time objects 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 use 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:

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 the ColdFusion Now function
returns an ODBC timestamp:

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 run time, the Java virtual machine 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 virtual machine 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 example:

<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: Boolean, int, long, float, double, and String.

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

Using quotation marks

To ensure that ColdFusion properly interprets string data, surround strings in single- or double-quotation marks. 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

"Five is " & 5

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

Example 3

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-time object. One is added to the date-time object, moving it ahead by one day to October 31, 2001.

 Adobe

Get help faster and easier

New user?