5
votes

I normally don't work in ColdFusion but there's a FTP process at work I have to create a report for with the only option right now being a ColdFusion 8 server. This FTP feed has a few issues (trash too).

So, I make the query and then I need to convert some of the string values during the output to do some math. Before that:

How do I tell if a field in the output loop: is not blank or null, is string that can be converted into a valid number, and is not 0?

Is there a simple way of doing this w/o a lot of if statements?

Thanks!

4

4 Answers

10
votes

So you want to make sure that the variable is numeric but not zero?

Then you want this:

<cfif IsNumeric(MyVar) AND MyVar NEQ 0 >
5
votes

Determining if a string is not null/blank and is a number and not 0?

Here's the code I would use in this case.

<cfif isDefined(stringVar) and len((trim(stringVar))) and isNumeric(stringVar)>
    do stuff here
</cfif>

isDefined returns a true if the variable exists. If you know the scope of the variable, i.e., its in the form or url scope for instance, you can use structkeyExists(form,"stringVar"). I would recommend using this approach if you know the scope of the variable.

Len(trim(stringVar)) is the second check. First off it trims any leading or trailing empty spaces from the string - this makes sure that any empty variables are not passed along. Then if something is there it will return the length of the string. If its empty len will return a 0.

isNumeric(stringVar) returns a true if the variable is a number and false otherwise.

0
votes
<cfif isNumeric(myfield) and myfield gt 0>
0
votes
<cfif Len(field) and Val(field)>

Len() will verify the field has length (not blank--there are no NULLs in CF) and Val() will automatically convert the first character in the string into into a number--or return 0 if it cannot.

Take note of Peter's comment below; although this is the least verbose answer, Val() may fail in certain edge conditions below, ie. The field is a string but starts with a number, incorrectly converting it to a number, and evaluating to TRUE.