double to string in C++ 14
In C++14, you can convert a double
to a std::string
using the std::to_string
function, which is part of the standard library. Here's a simple example to demonstrate this:
#include <iostream>
#include <string>
int main() {
double myDouble = 3.14159;
std::string myString = std::to_string(myDouble);
std::cout << "The double as a string is: " << myString << std::endl;
return 0;
}
In this example:
<iostream>
for input/output operations and <string>
for the std::string
class.double
variable myDouble
and initialize it with a value.std::to_string
to convert the double
to a std::string
and store the result in myString
.The std::to_string
function is straightforward and convenient for converting numeric values to strings. However, it may not provide the level of control over formatting that you might need in some cases. If you need more control over the formatting (e.g., specifying the number of decimal places), you can use string streams:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
int main() {
double myDouble = 3.14159;
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << myDouble;
std::string myString = oss.str();
std::cout << "The double as a string with 2 decimal places is: " << myString << std::endl;
return 0;
}
In this example:
<sstream>
and <iomanip>
headers for string stream and formatting utilities.std::ostringstream
object to build the string.std::fixed
and std::setprecision
to control the formatting of the double
.std::string
using the str()
method of the std::ostringstream
object.This approach gives you more control over the formatting of the output string.