March 2, 2008

Converting boolean values to numeric equivalents

Today I had a situation where I wanted to convert a boolean value (true or false) to a numeric equivalent (1 or 0) for insertion into a database table field which had a “tinyint” data type.

The value was coming from a form checkbox, so the actual element may or may not exist in the form struct depending on whether the user “checked” the box or not.

I found a few ways to do this, some “better” than others but all using structKeyExists() to look for the form element. The result of which will of course return a boolean “true” if the key exists within the form struct (meaning the user has checked the checkbox) or “false” which tells me the checkbox was unchecked (or simply not checked in the first place).

The long way round, arguably less elegant:

<cfif structKeyExists(form, 'minimised')>

Using the ColdFusion iif() equivalent of a conditional “ternary operator”

#iif((structKeyExists(form, 'minimised')), 1, 0)#

Casting the value using javaCast():

#javaCast('int', structKeyExists(form, 'minimised'))#

Doing a numberFormat():

#numberFormat(structKeyExists(form, 'minimised'))#

The last 2 examples seem like the best approach to me as they are more succinct than using an / combination, and most people shy away from iif() because it will evaluate() either of the string expressions (in this case 1 or 0) which is irrelevant for your needs in many cases including this one.

© Michael Sharman 2017