Sometimes, while working with data with your 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!
HOW TO CONVERT A STRING TO 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 Raspberry PLC, or from others inputs or outputs from some other Arduino, ESP32 or Raspberry PLC 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!