How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?
For example: 3.14159265359 -> "3.14"
We can convert float to String in java using String. valueOf() and Float. toString() methods.
We can convert float to a string easily using str() function.
Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.
We can convert float and double to string using the C++11 std::to_string() function.
A typical way would be to use stringstream
:
#include <iomanip> #include <sstream> double pi = 3.14159265359; std::stringstream stream; stream << std::fixed << std::setprecision(2) << pi; std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the
floatfield
format flag for the str stream tofixed
.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:
#include <array> #include <charconv> double pi = 3.14159265359; std::array<char, 128> buffer; auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi, std::chars_format::fixed, 2); if (ec == std::errc{}) { std::string s(buffer.data(), ptr); // .... } else { // error handling }
The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstream
something like:
std::stringstream ss; ss << std::fixed << std::setprecision(2) << number; std::string mystring = ss.str();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With