Truncate/round double variables to 2 decimals in Particle.publish?


#1

I’ve read through more than a few threads on similar topics, but this just isn’t sticking for me.

I’ve got two double variables stored globally in my ino file:

double tempC;
double relH;

then in my setup() i have two variables for Particle:

Particle.variable(“temperatureC”, tempC);
Particle.variable(“relhumid”, relH);

the part I can’t seem to solve is:

//attempt to convert and publish temperature in C double variable as 2 digit decimal
char chartempC[10];
sprintf(chartempC, "%.2f", tempC);
Particle.publish("temperature", chartempC);

//attempt to convert and publish relative humidity double variable as 2 digit decimal
char RH[10];
sprintf(RH, "%.2f", relH);
Particle.publish("relative_humidity", RH);

is this the appropriate (smartest? shortest?) way to get 2 decimal places on these variables?

is there an easy way to round double variables to 2 decimal places before you save data to an SD card?

Excuse the questions if its a simple thing, I’m rather new to all of this. Thanks for the help in advance, I’ve learned a lot from all the people sharing solutions on here :slight_smile:

~D


#2

I’d say sprintf(buffer, "%.2f", dbl) is probably the best way to do it, but this use falls short of the whole potential of sprintf().
But for the smartest way to publish (not knowing where you publish too), I’d suggest this instead

  char data[64];
  snprintf(data, sizeof(data), "t: %.2f°C, h: %.2f%%", tempC, relH); // output: t: 12.34°C, h: 45.67%
  Particle.publish("envData", data, PRIVATE);