Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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">
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment