+ 7
How can one set the precision of a long double number contained in a string?
I have a string, and I wish to save a number ( type - long double ) into it. I use : std::string res; long double val; res = std::to_string(val); But, if my number val is 3.14, I get a 3.140000. I know thats the default precision. But the string is retaining the precision even when I use cout.precision(2). I have to use the string later in a SetWindowText() operation. So shall I redefine a to_str() function using ostringstream and set the precision before writing or is there a simpler way?
8 odpowiedzi
+ 4
@Ace
So thats the only way, right sir?
Ill now use stringstream. Thank You!
+ 4
@Zeke Williams
If I could use that, I would not need to ask this question. But my output is of the following form :
SetWindowText(hWnd, const_cast<char*>(mystr.c_str()));
I tried using setprecision() and cout.precision(), but none work for SetWindowText().
+ 3
I use:
#include <iomanip>
...
cout << fixed;
cout << setprecision (2) << doubVar << endl;
And this works for me every time. The std::fixed ensures that no matter how many numbers are in front of the decimal, the same number specified in setprecision will come after the decimal.
+ 3
@Ace
But by far, is stringstream the smallest way?
I wish to use the approach with minimum number of lines used. So far, to_string was the smallest, but it cannot grant me a custom precision. So Ill use stringstream now.
+ 2
Ah yes, I didn't quite read exactly what you wanted. This is a new experience for me