Friday, February 26, 2016

ColdFusion Val function limitations

I was recently working with some really small numbers in ColdFusion and found that one of my typical shortcuts was actually causing me problems. Since I would retrieve information from the database and the database would return an empty string when the value was NULL, I would use ColdFusion's Val function to quickly make sure that any blank strings would become zeroes before I did arithmetic with them.

As mentioned above, the problem arose when I started working with really small numbers. As I'm sure most ColdFusion developers know, the language is loosely typed. If you want to display the value of a variable, ColdFusion transparently casts the variable as a string. If you want to perform arithmetic on a variable, ColdFusion transparently casts the variable as a number. If you want to perform date manipulation on a variable, ColdFusion transparently casts the variable as a date.

What I found regarding the Val function was that, when I was working with numbers small enough that they would be displayed in "exponent format" (a significand, followed by E, followed by the exponent), Val would only return the significand. Val was taking the string representation of the number and stopping at "E" because that is a non-numeric character. This isn't terribly unexpected, but has reduced the usefulness of the function for me.