Calculate precentage

Hi!
I wan't to calculate the precentage between two msg.payload numbers.
If i use the join node, I can join the two to an array, but then I am lost :slight_smile:
Often, the values are lik 0.75 and 0.18
How do I get the precentage of difference?

Hi @dowermyr

lets put aside the node-red part of this and just clarify your question. What do you mean by the percentage of difference between the two numbers?

If you have 0.75 followed by 0.18, the difference between the two is 0.57. What do you want that to be expressed as a percentage of?

Can you explain how you want to use this value?

I want to know how much procentage the higher value is based on the lower

Den mĂĄn 28 sep. 2020 14:55Nick O'Leary via Node-RED Forum <nodered@discoursemail.com> skrev:

So if you received the numbers 0.75 and 0.18, you would want to know that 0.75 is 316% larger than 0.18? And that would be same regardless of the order of the messages? You would always want the percentage increase from smaller number to larger number?

So if you have msg.payload containing the two numbers as an array (thanks to the Join node), then you could do:

// Find the min and max values in the `msg.payload` array:
const minValue = Math.min.apply(null,msg.payload);
const maxValue = Math.max.apply(null,msg.payload);

// Calculate the percentage change from min to max:
msg.payload = ((maxValue - minValue)/ minValue)*100;

return msg;

Thanks!
Works like a charm !