Sometimes, while working with data with your industrial Raspberry PLC, you realize that some nodes from Node-RED, like the MQTT nodes, send the information or need to get the data in a number format, not only the number as a string.
But how can you parse a string value to a number format without so much trouble using Node-RED? In this blog post, you will learn how to do it!
If you got to this blog post, you will not need to know what Node-RED is, and it is for, or how to install it. Otherwise, please visit Node-RED's website >>> for more information.
How to convert a string to a number
The string values to convert can come from multiple places: exec, inject, MQTT in nodes, etc. coming from sensors, from inputs or outputs of the industrial Raspberry Pi PLC, or from others inputs or outputs from some other Arduino, ESP32, or Raspberry Pi PLC controller using Modbus...
What we are going to do now, it is to send a string from an inject node with a String format, convert it to a number, and get it from a debug node.
So, you will only need three nodes:
Injects a message into a flow wither manually or at regular intervals.
Set, change, delete or move properties of a message, flow context or global context.
Displays selected message properties in the debug sidebar tab and optionally the runtime log.
These are the steps to follow in order to convert a string to a number with Node-RED:
1. First of all, add an inject node with a string msg.payload that can be converted to a number, for example, 123456.
2. Then, add a change node and set the msg.payload to JSONata Expression > Select the function reference: Number. > Click on Insert > Change the (arg) for payload like: $number(payload) > Click on Done.
3. Finally, add two debug nodes. One right after the inject node, and the other one after the change node. With this, we will be able to see both parsed values.
Now, click on the button of the inject node and Voilà! Your values will be converted from string to number!