Reputation: 795
I have been trying to convert a double into string without the C++11 (ToString) but it only accepts the number of decimals to be 5 as default. How can I change that?
The command is:
string a = static_cast<ostringstream*>( &(ostringstream()<<digits) )->str();
but it keeps 5 decimals while I want to create a string which has all the decimals (e.g. 100) I know that, that many decimals dont matter. This is one point of the exercise I was doing.
Any suggestions?
Thank you very much for your time Cheers!
Upvotes: 1
Views: 3119
Reputation: 795
This worked for me finally
digits = 1.12345123451234;
char buff[100];
sprintf(buff, "%1.14f", digits);
string a(buff);
Thanks for checking it in any case
Cheers
Upvotes: 0
Reputation: 3778
Use IO manipulators setprecision here on std::cout
but works on stringstream
:
// setprecision example from cplusplus.com
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::fixed << std::setprecision(9) << f << '\n';
return 0;
}
By the way, no double
will have 100 meaningfull digit, it's 15 or 17, I forgot exactly how many.
EDIT: I forgot, if you can use C++11... You can (and should) use to_string
#include <string>
// ....
std::string f_str = std::to_string(f);
Upvotes: 5