Shannon - 10 months ago 37

C++ Question

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

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

See fixed

Use fixed floating-point notationSets the

`floatfield`

format flag for thestrstream 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 theprecision field(`precision`

) and with no exponent part.

and setprecision.

Source (Stackoverflow)