# Function: division by 0

**URL:** <https://discourse.nodered.org/t/function-division-by-0/47365>\
**Category:** General\
**Created:** [19 June 2021 12:20 UTC](https://discourse.nodered.org/t/function-division-by-0/47365 "2021-06-19T12:20:16Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [19 June 2021 12:20 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/1 "2021-06-19T12:20:16Z")

</div>

I´m pretty new in Node-Red, but all I´ve done till now is working fine.  
Sometimes it´s easy to understand how it´s working, but now I´m having a problem with division by 0.  
My solution is working, but it must give a better one.

var CP = msg.payload["CP"];  
var CC = msg.payload["CC"];  
var COP;  
if(CP \> 0 || CC \> 0) { COP = (CP / CC); }  
else { COP = 0.0001; }  
msg.payload = COP  
msg.payload = msg.payload.toFixed(2);  
msg.topic = "Cool\_COP";  
return msg;

Because I´m using 2 decimal places I´m rounding.  
What´s a better solution ?  
Thanks.

With kind regards,  
Thorsten

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [19 June 2021 14:29 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/2 "2021-06-19T14:29:35Z")

</div>

> [@Crashy77](#):
>
> if(CP \> 0 || CC \> 0) { COP = (CP / CC); }

Consider this, CP = 2, CC = 0

your if statement will be true. Here is the equivalent in works  
if(2 \> 0 `or` 0 \> 0) { COP = (2 / 0); }

I suspect you meant...

```auto
if(CP > 0 && CC > 0) { COP = (CP / CC); }

```

or, more usually...

```auto
if(CC != 0) { COP = (CP / CC); }

```

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [19 June 2021 17:09 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/3 "2021-06-19T17:09:59Z")

</div>

Hi Steve.

I´ve tried your proposals.

no result/payload:

```auto
 if(CP > 0 && CC > 0) { COP = (CP / CC); }

```

NaN:

```auto
if(CC != 0) { COP = (CP / CC); }

```

You must know, that both can be 0.  
Cool power consumption (CC) and cool power production (CP) are 0 when heat pump is heating water.

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [19 June 2021 17:13 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/4 "2021-06-19T17:13:51Z")

</div>

> [@Crashy77](#):
>
> NaN

This means one of your values is not a number. Add `node.warn([CC,CP])` above the `if` statement to see what they contain (check debug output)

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [19 June 2021 17:30 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/5 "2021-06-19T17:30:34Z")

</div>

![flow](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/b/bbe48ef24027bc1d37cebf0921087d64955d2f90.jpeg)  
This is, what I´m getting in my way:  
 ![flow_payload](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/0/b00426de3b04ed0eb9e154c26c47795fd4eec94e.jpeg)  
And this is with your proposal:  
 ![flow_payload_yours](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/9/0/90b3f8f4af095b1e1a1968674904c674cd5a8411.jpeg)

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [19 June 2021 17:35 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/6 "2021-06-19T17:35:36Z")

</div>

So your msg.payload is an object containing `string` properties - strings are not ideal for number comparison & math functions.

Try this...

```auto
var CP = Number(msg.payload.CP);
var CC = Number(msg.payload.CC);
var COP = 0;
if (CC != 0) {
    COP = (CP / CC);
}
msg.payload = COP.toFixed(2)
msg.topic = "Cool_COP";
return msg;

```

TBH, you really should not be doing the `toFixed(2)` as you lose number precision and turn it into a string.

I would recommend keeping the full number until such a time as you display it (then to toFixed(2) or other formatting for display purposes)

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [19 June 2021 17:54 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/7 "2021-06-19T17:54:17Z")

</div>

Ok, that works, thanks.  
Maybe you can help me with my fault on Grafana.  
I´m getting the message "unsupported mean iterator type: \*query.stringInterruptIterator"

At that moment when I´m choosing a field variable, for example CC, I´m getting this message:  
Here´s the query inspector output:  
_Object_  
_request:Object_  
_method:"GET"_  
_url:"api/datasources/proxy/1/query"_  
_params:Object_  
_db:"iobroker"_  
_q:"SELECT mean("CC") FROM "Testing" WHERE time \>= now() - 1h GROUP BY time(2s) fill(null)"_  
_epoch:"ms"_  
_data:null_  
_precision:"ms"_  
_hideFromInspector:false_  
_response:Object_  
_results:Array[1]_  
_0:Object_  
_statement\_id:0_  
\*error:"unsupported mean iterator type: _query.stringInterruptIterator"_  
_executedQueryString:"SELECT mean("CC") FROM "Testing" WHERE time \>= now() - 1h GROUP BY time(2s) fill(null)"_

"Switch" is getting the information by MQTT:  
 ![switch](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/f/1/f1450459c93cccf51c5a144662f93fdc4300a3c9.jpeg)

function:  
_msg.payload = msg.payload;_  
_msg.topic = "HP";_  
_return msg;_

Next step depends on energy value for calculation the COP or going directly to join.  
Is it possible, that the string from "switch" is transfered to the influxdb out ?

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [19 June 2021 17:55 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/8 "2021-06-19T17:55:53Z")

</div>

> [@Crashy77](#):
>
> Is it possible, that the string from "switch" is transfered to the influxdb out

Possibly, probably. Have a look in the database.

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [19 June 2021 18:18 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/9 "2021-06-19T18:18:10Z")

</div>

no strings in the measurement.

So, why I´m getting this message by choosing a field variable ?

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [19 June 2021 20:10 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/10 "2021-06-19T20:10:38Z")

</div>

> [@Crashy77](#):
>
> no strings in the measurement.

Add a debug node showing what you are sending to the influx node and check that the values are not strings. Post the result here if you think it looks ok.

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [19 June 2021 20:45 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/11 "2021-06-19T20:45:32Z")

</div>

That's the payload after join:  
 ![flow_payload](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/0/b00426de3b04ed0eb9e154c26c47795fd4eec94e.jpeg)

When I´m debugging all messages I get this:

_DHW\_COP : msg : Object_  
_object_  
_topic: "DHW\_COP"_  
_payload: object_  
_qos: 0_  
_retain: false_  
_\_topic: "jeisha/main/DHW\_Energy\_Consumption"_  
_\_msgid: "c1817067.3aba"_

I´ve trying it in seperate steps and I´m getting the string by the switch node.  
But how can I read out a string from MQTT without giving it forward to other nodes ?

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [20 June 2021 07:21 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/12 "2021-06-20T07:21:28Z")

</div>

> [@Crashy77](#):
>
> That's the payload after join:

If that is what you are sending to influx, then, as you can see, it is showing values such as  
`HP: "0"`  
so the value being sent to influx is indeed a string not a number. If it were a number it would appear as  
`HP: 0`  
So the values in the the database are strings not numbers so you cannot use influx query functions such as mean. The solution is to convert them all to numbers before sending to influx.

On a separate issue related to your flow, do all the values come in to node-red together or are they coming at different times and you are joining them together? If they arrive at different times then you should write them to separate Measurements in influx. If they are arriving together then you should not split them up and join them together again, but should extract the data direct from the incoming message.

Also you should generally not round the data before writing to influx, you should always keep the data to maximum precision in the database. You can round it when you inspect it later if necessary.

Finally you should generally not write derived values to the database as well as the source data (such as CP, CC and Cool\_COP) but should derive it when you use it. There are occasions when it is worth while to save derived data, but generally it is considered a bad idea.

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [20 June 2021 09:07 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/13 "2021-06-20T09:07:18Z")

</div>

In my flow the output of the 1st function is a number.  
So in your opinion I should use a function directly behind the first function without join?  
How can I call the variable as a number ? Number(msg.payload.CP) ? Because that´s not working.

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [20 June 2021 09:11 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/14 "2021-06-20T09:11:35Z")

</div>

> [@Crashy77](#):
>
> How can I call the variable as a number ? Number(msg.payload.CP)

```auto
msg.payload.CP = Number(msg.payload.CP);

```

or

```auto
msg.payload.CP = parseInt(msg.payload.CP);

```

do that in the same function before `return msg`

You should probably do that to all variables in the payload object.

  

NOTE: I did say...

> [@Steve-Mcl](#):
>
> I would recommend keeping the full number until such a time as you display it

... what i didnt say was - because if you store the data in a database, it will be in-accurate and potentially the wrong format (it was implied 😉 )

  

EDIT...  
What Colin is alluding to, is often, with influx, the values are stored individually - e.g. instead of joining CC and CP data, write those as individual measures. Then, only when you retrieve and display them do you do any formatting or compound values.

EDIT2...

I suspect the functions called CP and CC are probably converting the values to strings (or, if not, then perhaps inside that function you should do the number conversions before spitting them out)

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [20 June 2021 09:50 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/15 "2021-06-20T09:50:30Z")

</div>

In first function it´s:

```auto
msg.payload = Number(msg.payload);
msg.topic = "CP";
return msg;

```

and I´m getting a number. If I´m using

```auto
msg.payload.CP = Number(msg.payload);

```

in the 1st function, then it´s a string.  
So what´s the best function code for CooL\_COP without using the first join ?

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [20 June 2021 09:56 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/16 "2021-06-20T09:56:21Z")

</div>

> [@Crashy77](#):
>
> So what´s the best function code for CooL\_COP without using the first join ?

It all depends on what you are doing with data, how you display it etc.

Colins advice was to send the CC and CP values individually to influx (skip the join node)

then when you query the database, do a join in your QUERY.

Once you have the data coming back to node, red, you compute the Cool\_COP value.

* * *

NOTE: I dont understand your entire requirements nor am I fully up to speed with infuxDB - in relational DB terms (mySQL / SQL Server) I would probably have a VIEW or STORED PROCEDURE that returns the data joined and the COOL\_COP calculated in the QUERY at the database side (since it is much faster)

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [20 June 2021 10:07 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/17 "2021-06-20T10:07:53Z")

</div>

Why it´s better to use 3 or more measurements instead of 1 for all 9 values ?  
How can I get a number after COP instead a string ?  
Here´s an example, what´s not working:

```auto
[
    {
        "id": "ee4a7550.dfd258",
        "type": "tab",
        "label": "Flow 4",
        "disabled": false,
        "info": ""
    },
    {
        "id": "541813a6.e0b86c",
        "type": "switch",
        "z": "ee4a7550.dfd258",
        "name": "Heat_Energy_Production",
        "property": "topic",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "jeisha/main/Heat_Energy_Production",
                "vt": "str"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 1,
        "x": 590,
        "y": 240,
        "wires": [
            [
                "ac0219a8.543438",
                "e09d0e03.75c14"
            ]
        ]
    },
    {
        "id": "2c1a2d2d.641392",
        "type": "switch",
        "z": "ee4a7550.dfd258",
        "name": "Heat_Energy_Consumption",
        "property": "topic",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "jeisha/main/Heat_Energy_Consumption",
                "vt": "str"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 1,
        "x": 600,
        "y": 280,
        "wires": [
            [
                "d97d92b2.f24e9"
            ]
        ]
    },
    {
        "id": "ac0219a8.543438",
        "type": "function",
        "z": "ee4a7550.dfd258",
        "name": "HP",
        "func": "msg.payload = Number(msg.payload);\nmsg.topic = \"HP\";\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 810,
        "y": 240,
        "wires": [
            [
                "629eda30.603894"
            ]
        ]
    },
    {
        "id": "d97d92b2.f24e9",
        "type": "function",
        "z": "ee4a7550.dfd258",
        "name": "HC",
        "func": "msg.payload = Number(msg.payload);\nmsg.topic = \"HC\";\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 810,
        "y": 280,
        "wires": [
            [
                "629eda30.603894"
            ]
        ]
    },
    {
        "id": "629eda30.603894",
        "type": "function",
        "z": "ee4a7550.dfd258",
        "name": "Heat_COP",
        "func": "var HP = msg.payload.HP;\nvar HC = msg.payload.HC;\nvar COP = 0;\nif(HC !=0) { COP = (HP / HC); } \nmsg.payload = COP.toFixed(2);\nmsg.topic = \"Heat_COP\";\nreturn msg;\n",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1030,
        "y": 260,
        "wires": [
            [
                "9157fb98.92f528"
            ]
        ]
    },
    {
        "id": "e09d0e03.75c14",
        "type": "debug",
        "z": "ee4a7550.dfd258",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": true,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "payload",
        "statusType": "auto",
        "x": 920,
        "y": 160,
        "wires": []
    },
    {
        "id": "9157fb98.92f528",
        "type": "debug",
        "z": "ee4a7550.dfd258",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": true,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "payload",
        "statusType": "auto",
        "x": 1300,
        "y": 320,
        "wires": []
    },
    {
        "id": "57f8a5dd.4af72c",
        "type": "mqtt in",
        "z": "ee4a7550.dfd258",
        "name": "Panasonic Aquarea",
        "topic": "jeisha/main/#",
        "qos": "0",
        "datatype": "utf8",
        "broker": "c61d6a73.c55788",
        "nl": false,
        "rap": true,
        "rh": 0,
        "x": 270,
        "y": 260,
        "wires": [
            [
                "541813a6.e0b86c",
                "2c1a2d2d.641392"
            ]
        ]
    },
    {
        "id": "c61d6a73.c55788",
        "type": "mqtt-broker",
        "name": "",
        "broker": "127.0.0.1",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "verifyservercert": true,
        "protocolVersion": "3",
        "keepalive": "15",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willPayload": "",
        "willMsg": {},
        "sessionExpiry": ""
    }
]

```

Please help me with this problem. I don´t understand why I´m getting the value as a string and how to solve it. Thanks.

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [20 June 2021 10:13 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/18 "2021-06-20T10:13:50Z")

</div>

> [@Crashy77](#):
>
> Why it´s better to use 3 or more measurements instead of 1 for all 9 values ?

It is a design thing (comes with experience) - see [this thread](https://stackoverflow.com/questions/45368535/influxdb-single-or-multiple-measurement)

  

* * *
  

> [@Crashy77](#):
>
> I don´t understand why I´m getting the value as a string

Reason...  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/6/6/6650baefebca12fd06349487d03f5cff49eb8829.png)

As I said before...

> [@Steve-Mcl](#):
>
> TBH, you really should not be doing the `toFixed(2)` as you lose number precision and turn it into a string.
> 
> I would recommend keeping the full number

... to be 100% clear - delete `.toFixed(2)` and it WILL be a number.

---

<div class="post-metadata">

**Author:** ![Crashy77](https://avatars.discourse-cdn.com/v4/letter/c/bcef8e/32.png) [@Crashy77](https://discourse.nodered.org/u/Crashy77)\
**Post date:** [20 June 2021 10:29 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/19 "2021-06-20T10:29:13Z")

</div>

Sorry, dude, but it´s still a string 😉

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [20 June 2021 10:32 UTC](https://discourse.nodered.org/t/function-division-by-0/47365/20 "2021-06-20T10:32:53Z")

</div>

paste the updated flow (just the relevant parts)

and

capture the MQTT message that feeds into it by doing this...

1. add a debug to the output of the MQTT IN

2. set the debug to show complete message

3. press the `copy value` button that appears under your mouse when you hover on thew debug message object  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/e/d/edaf159c628b3374eb979f10147db6571982c1d3.png)

4. paste the copied data into a reply with your flow

[Next page](https://discourse.nodered.org/t/function-division-by-0/47365.md?page=2)
