简体   繁体   中英

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.

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);

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++ (ie, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM