如何将浮点转换为字符串

Mic*_*Man 2 c++

如何将浮点转换为字符串,并在浮点为圆数时添加2位小数.目前我正在使用以下内容,但对于整数,我希望添加.00.我需要为此编写自己的例程吗?

float floatingNumber = 1.00;
string string;
ostringstream stream;

stream << floatingNumber;
string += stream.str(); // result is 1 not 1.00
Run Code Online (Sandbox Code Playgroud)

For*_*veR 7

您应该手动设置精度并使用标志,允许您使用 fixed notation

setprecision 固定

stream << std::fixed << std::setprecision(2) << floatingNumber;
Run Code Online (Sandbox Code Playgroud)