views:

51

answers:

2

The following function was suggested to me:

' Defines a forced casting function, which "casts" anything that it can't detect as a number to zero.
    Function MakeInteger(val)
      If IsNumeric(val) Then
        MakeInteger = CInt(val)
      Else
        MakeInteger = 0
      End If
    End Function

Unfortunately there appear to be some things that return true for IsNumeric() but still can't be cast as an int. Is there any better check to use?

+1  A: 

See here for 'what is wrong with isnumeric' about this. They give this solution:

<% 
    function isReallyNumeric(str) 
        isReallyNumeric = true 
        for i = 1 to len(str) 
            d = mid(str, i, 1) 
            if asc(d) < 48 OR asc(d) > 57 then 
                isReallyNumeric = false 
                exit for 
            end if 
        next 
    end function 

    response.write isReallyNumeric("3e4") & "<p>" 
    response.write isReallyNumeric("3d4") & "<p>" 
    response.write isReallyNumeric("&H05") & "<p>" 
    response.write isReallyNumeric("$45,327.06") & "<p>" 
    ' and a sanity check: 
    response.write isReallyNumeric("1234") & "<p>" 
%>

You'll have to adjust if you want to accept certain characters as 'numeric', e.g. commas, decimal points, + and - signs, etc.

Preet Sangha
+2  A: 
function TryCInt( str )
   TryCInt = 0
   On error resume next
   TryCInt = cint( str )
end function
Eduardo Molteni