Convert double to string using boost::lexical_cast in C++?(在 C++ 中使用 boost::lexical_cast 将双精度转换为字符串?)
问题描述
我想使用 lexical_cast
将浮点数转换为字符串.通常它工作正常,但我对没有小数的数字有一些问题.如何修复字符串中显示的小数位数?
I' d like to use lexical_cast
to convert a float to a string. Usually it works fine, but I have some problems with numbers without decimal. How can I fix number of decimal shown in the string?
示例:
double n=5;
string number;
number = boost::lexical_cast<string>(n);
结果编号是5
,我需要编号5.00
.
Result number is 5
, I need number 5.00
.
推荐答案
来自 提升 lexical_cast:
对于更复杂的转换,例如需要比 lexical_cast 的默认行为提供的更严格控制的精度或格式,建议使用传统的 stringstream 方法.在数字到数字的转换中,numeric_cast 可能提供比 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++ 中使用 boost::lexical_cast 将双精度转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中使用 boost::lexical_cast 将双精度转换为字符串?


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01