-1

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!

buzzard51
  • 1,372
  • 2
  • 23
  • 40

2 Answers2

1

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);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0
var num = 74.3; //=> typeof num "number"

var converted = String(num); //=> typeof converted "string" "74.3"

In your case, just do:

msg.payload = String(tempReading); 
johnny_mac
  • 1,801
  • 3
  • 20
  • 48