Problems using '.toFixed()'

Hi, I'm new using Node-Red and I'm having problems triying to reduce the number of decimals in a sum.

Here is my code but if I only receibe messages of undefined value

var m = {payload:msg.payload.col31};
var g = {payload:msg.payload.col32};
var h = {payload:msg.payload.col33};
m.topic = 'Altura 1'
g.topic = 'Altura 2'
h.topic = 'Altura 3'
var sum = {payload:msg.payload.col31+msg.payload.col32+msg.payload.col33};
sum.topic = 'suma'
//sum = Math.round(Number(sum))
//sum = parseFloat((sum.payload).toFixed(1));
//sum = String(sum);
return [m,g,h,sum];

A lot will depend on the message you're passing into the function. Can you share an example so we know what it is receiving?

it is a message from a CSV file, but the problem is that when I made the sum of 3 colums the result have alot of decimals .


Unfortunately you have not shown us the contents of col31, 32, 33 which are the ones used in the function. Also show us the output of the function node which shows undefined.

Note that the commented out lines such as
sum = Math.round(Number(sum))
would not have worked because sum is a message not a number. This shows the desirability of using meaningful names such as msgsum to remind you what things are.

here are the values of the colums

the output is a big number, only when I try to reduce the number of decimals is when the output is undefined, probably because you said, sorry i'm pretty new here and I'm learning

As Colin has said, in the code you shared, you were trying to perform those operations on sum which is an object, not a number. You need to operate on sum.payload as that is where your values are.

tried to use sum.payload but still receibe the message of undefined.

oooohhh forget it works perfectly, thanks for your help and patience.

Just a final word, as a general rule don't worry about reducing the precision of numbers until you get to the point of actually displaying it. Usually there will be a way of specifying how you want things displayed when you get to that stage. For example, if you are using the dashboard text node then you can specify the fact that you want two digits in the node definition itself.

Really? how do you that? because I tried but never saw the option to trim the number long.

If for example, you are displaying the value in a dashboard text node, you can always use angular filters to format the number.
Adding {{msg.payload | number:1}} mph to the text node value format box will format a msg.payload from 18.31158 to 18.3 mph


wow this will be very helpfull, thanks, you saved me

Wow. I just saw this. you changed my whole world with that comment. Much appreciated!


I added this into gauge node and it works perfect.


Is it possible to do something like this inside a Mustache template?

Mustache is not made for these kinds of things, because it is intended to be logic-less.
So no, not without ugly hacks!

What are you doing with the value after the template?