gpt4 book ai didi

c++ - 在 C++ 中使用 boost::lexical_cast 将 double 转换为字符串?

转载 作者:IT老高 更新时间:2023-10-28 22:31:58 26 4
gpt4 key购买 nike

我想使用 lexical_cast 将 float 转换为字符串。通常它工作正常,但我对没有小数的数字有一些问题。如何修复字符串中显示的小数位数?

例子:

double n=5;
string number;
number = boost::lexical_cast<string>(n);

结果编号是5,我需要编号5.00

最佳答案

来自 boost lexical_cast 的文档:

For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast.

例子:

#include <sstream>
#include <iomanip>

int main() {
std::ostringstream ss;
double x = 5;
ss << std::fixed << std::setprecision(2);
ss << x;
std::string s = ss.str();
return 0;
}

关于c++ - 在 C++ 中使用 boost::lexical_cast 将 double 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5016464/

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