Function node simple math operation?



new here and to node-red.

I've got a sense hat for my Pi 3b+ and want to add a simple minus operation to the temperature sensor on the hat as kind of a correction factor. Basically (temperature - 5) = CorrectedTemp.
Not sure how to put the code into the function node.

This is how the function node looks like now:

var o = msg.payload
msg.payload = o.temperature
return msg;



Assuming msg.payload.temperature contains a number with your temperature, you are nearly there already. :grinning:

msg.payload = o.temperature - 5 should do the trick.

1 Like
#3 that make me blushing. Tried in all variations, just not that one.

You're a gem :slight_smile:

1 Like

You're welcome!

BTW: If you want to keep the message structure as-is, don't overwrite the payload, just set the payload property to the new value.

msg.payload.temperature = msg.payload.temperature - 5;
return msg;
1 Like

Alternatively you can use a Range node to do the offset, avoiding the use of a function node.

1 Like

Or a Change node with a JSONata expression. Endless possibilities. :grinning:


I see. This seems to be an endless playground. And when one have no idea about coding at all, makes it even more fun :smiley:

Now I only need to get rid of the decimals and limit that to 1 or 2.


Thanks, Colin.
This helped also giving me Integers now. Great.


That is why I like to describe Node-RED as a very mysterious and powerful device and it's mystery is exceeded only by it's power. :sunglasses:

1 Like

Best not to do that till you are displaying it. If you are using the dashboard nodes you can specify the precision in the node itself.

1 Like

I guess that's what the Value Format is designed for. Will play with all variants and see the difference.


Function nodes are JavaScript running in a Node.JS VM. See the Mozilla Development Network website for more help on JavaScript than you could ever imagine!

Node-RED is a great way to get into JavaScript as you can let various nodes take care of the difficult, complex bits leaving you to think about specific bits of logic.

1 Like

It works fine with the gauge node as it allows me to set Value format and specify the number of decimals. Unfortunately the chart node does not have the option to specify the precision and when hover over into the chart, it displays all decimals. Not a big deal, but doesn't look nice.

Any other suggestions to get rid of the decimals at the output/display level for a chart node?


I don't know much about the chart node. It may be that you have to format it in a function node or similar first. Possibly a bit of a deficiency in the chart node.


Yes, seems like. I should make a feature request if it was important.