C ++ float for string with specific length

Here is my problem: I want to write a float with max 2 decimal places in a string and print it without a pair of 0 followed by a number.

How am I doing this 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); 

What prints: 15.56000000

HPDF_Page_ShowText is the HPDF_Page_ShowText open source library team for creating PDF documents. It expects (page-object, *const char) . That is why you must first convert the string to const char* .

I really searched the Internet for similar problems, but did not find anything suitable for myself.

+5
source share
1 answer

Use std :: stringstream and std :: setprecision () 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 variable const char* can be obtained through:

 const char* c = s.c_str(); 

Update:
Prefers std::ostringstream , as the stream is used for output only.

+5
source

Source: https://habr.com/ru/post/1271593/


All Articles