Here my problem: I want to write a float with max 2 decimal places into a string and print it without a couple of 0's behind the number.
The way I do it at the moment:
Values Material; // Class 'Values', Object 'Material'
Material.Temp = 15.56; // 'Temp' = float
string ss = to_string(Material.Temp); // Conversion to string
const char* cNumber = ss.c_str(); // Conversion to const char
HPDF_Page_ShowText(page, cNumber);
That prints out: 15.56000000
HPDF_Page_ShowText
is a command of the open source library libharu to create PDF-Documents. It expects (page-object, *const char)
. That is the reason why the string has to be converted into a const char*
first.
I really searched in the internet for similar problems, but found none that fit to mine.
Use a std::stringstream and std::setprecision() function in combination with the std::fixed stream manipulator:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
int main(){
float myfloat = 15.56f;
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << myfloat;
std::string s = ss.str();
std::cout << s;
}
The const char*
variable can be obtained via:
const char* c = s.c_str();
Update:
Prefer std::ostringstream
since the stream is used only for the output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With