Best way to check if value is integer ? Coldfusion 9

折月煮酒 提交于 2019-12-08 03:20:46

问题


I have fields to test and make sure they only accept integers. There is few functions but I wasn't sure which one is the best. First I tried isValid("integer",value) but I have discovered that "1,5" will be accepted as an integer. So then I tried isNumeric(value) but this will accept values like 1.5. I'm wondering what should be the best way to check for integers? Maybe two combine these two functions like:

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

Or there is better way to do this?


回答1:


You could try this:

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

Note People often include commas in large numbers such as 1,000,000. isNumeric will return false for that string, as will the refind function in the other answers.




回答2:


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 making sure the input is a primitive type (by CF means), because all numbers are considered simple values in CF (string conversion)
  • reFind regular expression checking digits-only (with or without sign), minimum of one digit, maximum of ten digits (implicit call of toString here)
  • check the range, all numeric types fit into 4 Bytes, thus no need to "upgrade" the type (as you would need to with BigInteger, BigDecimal etc.)

If you don't need the range check for 4 Byte integers, @DanBracuk posted an answer with a function that performs around 5-6 times faster than this one.




回答3:


Here's the isInteger UDF that I prefer using:

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

Here are some tests to determine how it functions and compares against the various built-in functions.

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

View the results using TryCF.com

https://trycf.com/gist/fab1104a3a9074434ff336630dd5ffd1



来源:https://stackoverflow.com/questions/46124664/best-way-to-check-if-value-is-integer-coldfusion-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!