检查值是否为整数的最佳方法是什么? Coldfusion 9

时间:2017-09-08 21:17:16

标签: coldfusion integer coldfusion-9 isnumeric

我有要测试的字段,并确保他们只接受integers。功能很少,但我不确定哪一个是最好的。首先我尝试isValid("integer",value),但我发现“1,5”将被接受为整数。所以我尝试了isNumeric(value),但这会接受像1.5这样的值。我想知道检查整数的最佳方法是什么?也许两个结合这两个函数,如:

<cfif isValid("integer",value) AND isNumeric(value)>

或者有更好的方法来做到这一点?

3 个答案:

答案 0 :(得分:5)

CFSCRIPT

// Returns if the provided value is a signed integer up to 32 Bit.
function isINT(any value) {

    return (
        isSimpleValue(ARGUMENTS.value) &&
        (reFind("^\-?[0-9]{1,10}$", ARGUMENTS.value) > 0) &&
        (ARGUMENTS.value <= 2147483647) &&
        (ARGUMENTS.value >= -2147483648)
    );
}

cftag

<cffunction name="isINT" access="public" output="false" returnType="boolean"
    hint="Returns if the provided value is a signed integer up to 32 Bit.">

    <cfargument name="value" type="any" required="true">

    <cfreturn (
        isSimpleValue(ARGUMENTS.value) and
        (reFind("^\-?[0-9]{1,10}$", ARGUMENTS.value) gt 0) and
        (ARGUMENTS.value lte 2147483647) and
        (ARGUMENTS.value gte -2147483648)
    )>
</cffunction>
  • isSimpleValue确保输入是基本类型(通过CF表示),因为所有数字都被认为是CF中的简单值(字符串转换)
  • reFind正则表达式检查仅数字(带或不带符号),最少一位数,最多十位数(此处隐式调用toString
  • 检查范围,所有数字类型都适合4个字节,因此无需&#34;升级&#34;类型(你需要使用BigInteger,BigDecimal等)

如果您不需要4字节整数的范围检查,@ DanBracuk发布了一个函数的答案,该函数的执行速度比此速度快5-6倍。

答案 1 :(得分:2)

这里是我喜欢使用的isInteger UDF:

function isInteger(num){
    return YesNoFormat(refind("^-?\d+$", num) AND VAL(num) LTE 2147483647 AND VAL(num) GTE -2147483648);
}

以下是一些测试,以确定它如何运作并与各种内置函数进行比较。

https://gist.github.com/JamoCA/fab1104a3a9074434ff336630dd5ffd1

使用TryCF.com查看结果

https://trycf.com/gist/fab1104a3a9074434ff336630dd5ffd1

答案 2 :(得分:1)

你可以试试这个:

value = replace(value, ',', '', 'all');
numberIsInteger = isNumeric(value) && round(value) == value ? true : false;

注意 人们经常包括大量的逗号,例如1,000,000。 isNumeric将为该字符串返回false,其他答案中的refind函数也将返回。