c++decimalroundingtrailing

removing trailing zeroes for a float value c++


I am trying to set up a nodemcu module to collect data from a temperature sensor, and send it using mqtt pubsubclient to my mqtt broker, but that is not the problem.

I am trying to send the temperature in a format that only has one decimal, and at this point I've succesfully made it round up or down, but the format is not right. as of now it rounds the temp to 24.50, 27.80, 23.10 etc. I want to remove the trailing zereos, so it becomes 24.5, 27.8, 23.1 etc.

I have this code set up so far:

#include <math.h>
#include <PubSubClient.h>
#include <ESP8266WiFi.h>


float temp = 0;

void loop {
  float newTemp = sensors.getTempCByIndex(0);

  temp = roundf((newTemp * 10)) / 10;
  serial.println(String(temp).c_str())
  client.publish("/test/temperature", String(temp).c_str(), true);

}

I'm fairly new to c++, so any help would be appreciated.


Solution

  • Regardless of what you do to them, floating-point values always have the same precision. To control the number of digits in a text string, change the way you convert the value to text. In normal C++ (i.e., where there is no String type <g>), you do that with a stream:

    std::ostrstream out;
    out << std::fixed << std::setprecision(3) << value;
    std::string text = out.str();
    

    In the environment you're using, you'll have to either use standard streams or figure out what that environment provides for controlling floating-point to text conversions.