Convert interegr to string w/o decimals

I posted this question on Stack Overflow first because it is not really a Particle issue but a simple programming issue, but Stack Overflow closed my post because it "needs clarity" (???).

My application running on a Photon2 needs to get an integer to appear on an LCD display without decimals. Specifically, I have a variable of type double - 'Percent' - that is calculated by diividing the number of 'Gallons' (also a double) in a water tank by the capacity of the tank times 100, as follows:

 Percent = (Gallons/1771*100)+.5; // Calculate percent full; .5 added to assure proper rounding   

Next, I try to convert Percent to an integer and then convert the integer to a string:

 int y = static_cast<int>(Percent); 
 std::string myString = std::to_string(y); 

Then my code tries to send the resulting string to an OLED display, as follows:

 display.getTextBounds((myString + "% Full"), 0, 0, &x1, &y1, &w, &h);
 display.setCursor((128 - w) / 2, 46);
 display.println(myString + "% Full");
 display.display();

Unfortunately, the code associated with the display won't compile (error = "no matching function for call to 'Adafruit_SSD1306::getTextBounds(std::__cxx11::basic_string)'".

How can I display only the integer component of the resulting myString value?

I think that's an issue with the SSD1306 library not accepting std::string. Try using a char[] instead.

#include <math.h>

double percent = (Gallons / 1771.0) * 100.0;
int y = (int)lround(percent);   // proper rounding

char line[24];
snprintf(line, sizeof(line), "%d%% Full", y);
2 Likes

I appreciate your input Eric and will try your suggestions. But I am curious: if you are correct about the SSD1306 library not accepting std::string, can you explain why the compiler only complains about line 158?

I believe it's because Arduino String and std::string are different.

Hmmmm. My head is starting to hurt. Stay tuned.

std::string is not commonly used in Particle and Arduino C++ code and there is no concatenation operator implementation for std::string + const char * in line 158.

It's more common to use Wiring String which does support string concatenation using +.

2 Likes

Thanks Rick. I'll try that too.