代码之家  ›  专栏  ›  技术社区  ›  Kzqai

在ASP Classic中:如何确保变量可以转换为int?

  •  1
  • Kzqai  · 技术社区  · 15 年前

    我建议使用以下功能:

    ' 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 回复  |  直到 15 年前
        1
  •  2
  •   Preet Sangha    15 年前

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

    如果你想的话,你得调整一下 接受某些字符为 “数字”,例如逗号、小数 点,+和-符号等。

        2
  •  2
  •   Eduardo Molteni    15 年前
    function TryCInt( str )
       TryCInt = 0
       On error resume next
       TryCInt = cint( str )
    end function
    
    推荐文章