Problems using '.toFixed()'

#1

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

0 Likes

Number of decimals i function
#2

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];

0 Likes

#3

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?

0 Likes

#4

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 .

foto1

0 Likes

#5

0 Likes

#6

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.

0 Likes

#7

here are the values of the colums
foto3

0 Likes

#8

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
foto4

0 Likes

#9

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.

0 Likes

#10

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

0 Likes

#11

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

0 Likes

#12

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.

0 Likes

#13

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

0 Likes

#14

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

2 Likes

#15

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

0 Likes