chapter31

development in a land far far away…

at the moment

History is not what happened. History is what was written down.

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:

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

Casting the value using javaCast():

Doing a numberFormat():

The last 2 examples seem like the best approach to me as they are more succinct than using an <cfif>/<cfelse> 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.


Related Pages

2 Responses to “Converting boolean values to numeric equivalents”

  1. Wouldnt have been easier to use cfparam?

    Raul Riera

  2. Yep, in this particular example I certainly could have used cfparam.

    It’s nice to have a few options for other scenarios though :)

    Michael Sharman

Leave a Reply