Shannon Shannon - 1 year ago 52
C++ Question

Convert float to string with set precision & number of decimal digits?

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"

Answer Source
double pi = 3.14159265359;
stringstream stream;
stream << fixed << setprecision(2) << pi;
string s = stream.str();

See fixed

Use fixed floating-point notation

Sets the floatfield format flag for the str stream to fixed.

When floatfield is 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.

and setprecision.