Rounding a float to 3 decimals and send through mqtt

I am trying to send the voltage of my esp8266 with some gpio details through mqtt. For this I am trying to round the voltage to decimal places and then send mqtt but not matter what I try, it doesn't round the voltage.

I have already defined every variables earlier which is not present in the below code. I get the mqtt payload for voltage as 3.29222455536 instead of 3.292

void setup() {
  voltage = (ESP.getVcc() - 140) * 0.001;
  voltage = round(voltage * 1000) / 1000;
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  if (!client.connected()) {
    reconnect();
  }
  status = digitalRead(13);
  if (status == 0) {
    JSONVar buttonPayload;
    buttonPayload["ID"] = deviceid + 1;
    buttonPayload["state"] = 0;
    buttonPayload["battery"] = voltage;
    jsonString = JSON.stringify(buttonPayload);
    client.publish(mqtttopic.c_str(), jsonString.c_str());
  } else {
    JSONVar buttonPayload;
    buttonPayload["ID"] = deviceid + 1;
    buttonPayload["state"] = 1;
    buttonPayload["battery"] = voltage;
    jsonString = JSON.stringify(buttonPayload);
    client.publish(mqtttopic.c_str(), jsonString.c_str());
  }
  delay(200);
  ESP.deepSleep(0);
  delay(200);
}

the strange thing is that I use the same rounding function at another place in the code and there it works fine.

I suggest to start by turning the number into a properly formatted C-string using snprintf() or dtostrf().

Can you explain a bit more?

you probably get lucky with the floating point representation
What’s the issue with sending the value as it stands without rounding? If it’s really an issue then use one of the function suggested by @jremington

That is my requirement.

Then

Or String(voltage,3)

1 Like

It seems odd to multiply by 0.001 (1/1000) and then multiply by 1000. if "ESP.getVcc()" returns an integer number of millivolts then it is already volts truncated to three decimal places.

I would change the definition of your JSON to keep the voltage in integer millivolts.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.