Skip to content

Instantly share code, notes, and snippets.

@GaryStanton
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GaryStanton/f2371ad529756c1f79a3 to your computer and use it in GitHub Desktop.
Save GaryStanton/f2371ad529756c1f79a3 to your computer and use it in GitHub Desktop.
Returns the closest number in a list to the given value - CFML
<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