Basic adding (sum) of var values/numbers using function node

I've been testing for hours now and just cannot seem to find a solution. I'm missing something but just do not get it. Please assist (I'm a beginner) with Node-red.

I want to calculate the total costs, so add up of all 4 values:

const globalHomeAssistant = global.get('homeassistant');
var dag = globalHomeAssistant.homeAssistant.states["sensor.stroomverbruik_maandelijks_dag"].state;
var nacht = globalHomeAssistant.homeAssistant.states["sensor.stroomverbruik_maandelijks_nacht"].state;
var gas = globalHomeAssistant.homeAssistant.states["sensor.monthly_gas_consumption"].state;
var water = globalHomeAssistant.homeAssistant.states["sensor.monthly_water_consumption"].state;

var water1 = Number(water * 0.604 + 46.04).toFixed(2); --this has value 46.33
var stroom1 = Number(dag * 0.14551).toFixed(2); --this has value 2.44
var stroom2 = Number(nacht * 0.13343).toFixed(2); --this has value 6.53
var gas1 = Number(gas * 0.75516).toFixed(2); --this has value 1.32

msg.payload_totale_kosten = (stroom1+stroom2+gas1+water1);

return msg;

but this gives me a result of: 2.446.531.3246.33
it is not a sum but just all number next to each other. I've tried many things, but none seem to work.

toFixed() returns a string.
So stroom1+stroom2+gas1+water1 concatenates the strings.
If you require the addition of 2 decimal place numbers use Math.round(Number(water) * 100) / 100.

1 Like

To add to what @E1cid says, dont reduce precision in the function. Only trim the decimal places when you view the result.

For example, get rid of all the .toFixed() functions, get the accurate result of the summation then (and only then) if you want to display the value in a friendly format do you reduce the precision.

If you want to display a value on the dashboard with reduced decimal places, you can use angular filters to make the value appear "nice". (Search the forum).

1 Like

Thanks all for the tips. I have it working now.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.