Last active
August 29, 2015 14:00
-
-
Save GaryStanton/f2371ad529756c1f79a3 to your computer and use it in GitHub Desktop.
Returns the closest number in a list to the given value - CFML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cffunction name="closestNumberInList" returntype="numeric" hint="Returns the closest number in a list to the given value"> | |
<cfargument name="Value" type="numeric" required="true" hint="A number to convert to the nearest in our list"> | |
<cfargument name="List" type="string" required="true" hint="A list of valid numbers we can return"> | |
<cfscript> | |
var Local = {}; | |
// Convert list to array | |
Local.ListArray = ListToArray(Arguments.List); | |
// Set up variable to hold the lowest difference | |
Local.LowestDifference = ''; | |
// Loop through array | |
For (Local.ThisNumber IN Local.ListArray) { | |
// Calculate difference between this and the value | |
Local.ThisDifference = abs(Local.ThisNumber - Arguments.Value); | |
// If the new calculated is lower than the existing, replace it. | |
if (NOT isNumeric(Local.LowestDifference) OR Local.ThisDifference LT Local.LowestDifference) { | |
Local.LowestDifference = Local.ThisDifference; | |
// Set return value | |
Local.ReturnVal = Local.ThisNumber; | |
} | |
} | |
return Local.ReturnVal; | |
</cfscript> | |
</cffunction> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment