question

diederik avatar image
diederik asked

Adding number

Hi,

I'm struggling with a simple math function in my Node Red flow.


This doesn't work:

maxBattery = ((80-(100*(sum/1000)/15.4)).toFixed(2))+20;
msg.payload = maxBattery;
return msg;

This does:

maxBattery = 80-(100*(sum/1000)/15.4)).toFixed(2);
msg.payload = Number(maxBattery)+20;
return msg;

Why?

Node-RED
2 |3000

Up to 8 attachments (including images) can be used with a maximum of 190.8 MiB each and 286.6 MiB total.

2 Answers
matt1309 avatar image
matt1309 answered ·

Hi @Diederik

Dynamic typing strikes again....


I'm pretty sure this is because javascript is treating first code snip you provided as a string so the + 20 is concatenating 20 as a string rather than evaluating the expression as you expect.

However you're telling JS maxBattery is of type Number in your second option so it's adding the number using addition not concatenation


This might make it easier to follow Assuming sum = 1000

Code snip 1:

maxBattery = ((80 - (100 * (1000 / 1000) / 15.4)).toFixed(2)) + 20
          = ((80 - (100 * 1 / 15.4)).toFixed(2)) + 20
          = ((80 - 6.493506493506493).toFixed(2)) + 20
          = ("73.51") + 20
          = "73.51" + "20"
          = "73.5120"

Code snip 2:

maxBattery = ((80 - (100 * (1000 / 1000) / 15.4) + 20).toFixed(2))
          = ((80 - (100 * 1 / 15.4) + 20).toFixed(2))
          = ((80 - 6.493506493506493 + 20).toFixed(2))
          = ((93.5064935064935 + 20).toFixed(2))
          = (113.5064935064935.toFixed(2))
          = "113.51"
1 comment
2 |3000

Up to 8 attachments (including images) can be used with a maximum of 190.8 MiB each and 286.6 MiB total.

diederik avatar image diederik commented ·
Code snip 2 was the way to do it. Thanks.
0 Likes 0 ·
diederik avatar image
diederik answered ·

Hi @matt1309,

Dynamic Typing :-)

I'm getting an array from the Solar Yield Forecast.

This is the complete function. Where do I start using strings?

var acThreshold = 400;
var sum = 0;
var toAdd = 0;

for (let i = 24; i < 48; i++) {
    if (msg.payload.records.solar_yield_forecast[i][1] > acThreshold){
        toAdd = msg.payload.records.solar_yield_forecast[i][1]-acThreshold;
    }
    else{
        toAdd = 0;
    }
sum += toAdd;
}

//maxBattery = ((80-(100*(sum/1000)/15.4)).toFixed(2))+20;
maxBattery = (80-(100*(sum/1000)/15.4)).toFixed(2);

msg.payload = Number(maxBattery)+20;
return msg;
1 comment
2 |3000

Up to 8 attachments (including images) can be used with a maximum of 190.8 MiB each and 286.6 MiB total.

matt1309 avatar image matt1309 commented ·

Hi @Diederik.


I believe it's literally the line you mention.

The toFixed(2)

method returns a string representation of the number with a fixed number of decimal places.


1 Like 1 ·