I have a node-red flow that needs to create an MQTT payload.
The payload is a temperature reading from an I/O card, calculated as a float (73.4 for example).
I need the message payload to be a string, not a number; something like "Barn Temp is 73.2". How can I create this?
msg.payload = tempReading; // gives a number
msg.payload = ""+tempReading; // returns NaN
A bonus question: if I did use this as a numeric payload how can I specify its format? The reading is calculated at 73.18527461364; I need to send this as 73.2.
I'm having a devil of a time finding out how to format strings in javascript!
toString
is an easy surefire way to convert numbers to strings.
var x = 10.56;
x = x.toString();
console.log(x, typeof x);
If you want to control how many decimal points are displayed, you can use toFixed
.
var x = 12.3456789;
x = x.toFixed(3);
console.log(x, typeof x);