Benja0906
Benja0906

Reputation: 1477

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.

Upvotes: 1

Views: 4715

Answers (3)

Pete Becker
Pete Becker

Reputation: 76305

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.

Upvotes: 1

Peter
Peter

Reputation: 36597

The library you are using is not part of standard C++. The String you are using is non-standard.

As Pete Becker noted in his answer, you won't be able to control the trailing zeros by changing the value of temp. You need to either control the precision when converting it to String, or do the conversion and then tweak the resultant string.

If you read the documentation for the String type you are using, there may be options do do one or both of;

  • control the precision when writing a float to a string; or
  • examine characters in a String and manually remove trailing zeros.

Or you could use a std::ostrstream to produce the value in a std::string, and work with that instead.

Upvotes: 1

Chris
Chris

Reputation: 963

It's unclear what your API is. Seems like you want to pass in the C string. In that case just use sprintf:

#include <stdio.h>

float temp = sensors.getTempCByIndex(0);
char s[30];
sprintf(s, "%.1f", temp);
client.publish("/test/temperature", s, true);

Upvotes: 2

Related Questions