Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  164] [ 7]  / answers: 1 / hits: 16059  / 7 Years ago, mon, january 30, 2017, 12:00:00

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!


More From » node.js

 Answers
180

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);




[#59149] Friday, January 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnaj

Total Points: 490
Total Questions: 109
Total Answers: 104

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;