Rounding a value to another value from a pre-defined table

Greetings. I am familiar with the various options and tools in Node-RED to do rounding of integers and floats, but can something like this be done?

Let's assume I record an integer between 957 and 1021. Can one create a function whereby the value is rounded (up or down) to the nearest of the 4 values shown below?

image

Something like this

//const values = [1021,1007,989,957]; //if equal round down
const values = [957,989,1007,1021]; //if equal round up
const output = {};
for(const num of values){
    output[Math.abs(msg.payload - num)] = num;
}
const minimum = Math.min(...Object.keys(output));
msg.payload = output[minimum];
return msg;

Or this is another solution in a few less lines

const values = [1021, 1007, 989, 957];
const value = msg.payload
const closest = values.reduce(function (prev, curr) {
    return (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);
});
msg.payload = closest
return msg;

Well one less anyway.

Thank you both! These work great for my needs.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.