How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?
3.14159265359 -> "3.14"
double pi = 3.14159265359; stringstream stream; stream << fixed << setprecision(2) << pi; string s = stream.str();
Use fixed floating-point notation
floatfieldformat flag for the str stream to
floatfieldis set to
fixed, 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.