gpt4 book ai didi

c++ - 如何将 float 转换为字符串

转载 作者:太空狗 更新时间:2023-10-29 23:52:16 25 4
gpt4 key购买 nike

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

float floatingNumber = 1.00;
string string;
ostringstream stream;

stream << floatingNumber;
string += stream.str(); // result is 1 not 1.00

最佳答案

您应该手动设置精度并使用标志,这样您就可以使用固定表示法

setprecision fixed

stream << std::fixed << std::setprecision(2) << floatingNumber;

关于c++ - 如何将 float 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16582640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com