在asp经典中:如何确保变量可以转换为int?

时间:2010-04-30 00:27:08

标签: asp-classic casting

我建议使用以下功能:

' 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

不幸的是,似乎有一些东西对IsNumeric()返回true,但仍然不能作为int强制转换。有没有更好的检查使用?

2 个答案:

答案 0 :(得分:2)

请参阅here for 'what is wrong with isnumeric'。他们给出了这个解决方案:

<% 
    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>" 
%>
  

如果你愿意,你必须调整   接受某些字符作为   '数字',例如逗号,十进制   点,+和 - 标志等。

答案 1 :(得分:2)

function TryCInt( str )
   TryCInt = 0
   On error resume next
   TryCInt = cint( str )
end function