Find the nearest value

Hi guys, Anyone know how to find the smallest different between the three input of decimal value? i try using min expression, but it returns the negative value because it show the lowest value.  The result should be like this.
1 answers

One solution could be putting numbers in form of an array. In Mendix, you can use a non-persistable entity with one decimal attribute to store the number. Now create a list of this entity. Each object holds one decimal numbers.

So , in this case it will be a list of size 3 having 3 numbers.

Sort this list in ascending order so largest number is at end. Now you can calculate smallest difference by

  • Create a variable difference
  • Loop on the list
    • In each iteration, calculate difference of current number and next number. Current number will be available in loop iterator object. You can find next by subtracting iterator object from list and taking head of this new list. Now you have difference of two numbers.
    • Check if this difference is smaller then previous stored difference, update your difference result variable.
    • At the end of each iteration, you have current minimum difference inside the list
  • At end of loop, you have found the minimum difference. This solution can work for greater than 3 numbers also. You just need a list/array of numbers

Below is a programmatic version of above algorithm if it may help you

for (let i = 0; i < numbers.length - 1; i++) {
    // Only calculate the difference between the next number and the current
    const latestDiff = numbers[i + 1] - numbers[i];

    // Only keep the diff if it's smaller than any we've seen up to this point
    smallestDiff = smallestDiff === null ? latestDiff : Math.min(smallestDiff, latestDiff);