Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ float to string with specific length

Tags:

c++

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.

like image 525
a.wemhoff Avatar asked Sep 07 '17 06:09

a.wemhoff


1 Answers

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.

like image 66
Ron Avatar answered Oct 11 '22 12:10

Ron