我想使用 lexical_cast
把浮点数转换成字符串。通常情况下这个函数能够正常工作,但是如果数字没有小数点,就会出现问题。我该怎么样才能控制在字符串中显示的小数位数呢?
例如:
double n=5;
string number;
number = boost::lexical_cast<string>(n);
结果编号为 5
,我需要数字5.00
。
根据Boost lexical_cast的文档:
对于涉及更复杂转换(例如需要比lexical_cast默认行为提供更紧密的控制精度或格式)的情况,建议使用传统的stringstream方法。如果转换是数值到数值的,则numeric_cast可能比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;
}
看看 boost::format 库。它把 printf 的易用性和流的类型安全结合起来。至于速度,我不确定,但我认为现在并不重要。
#include <boost/format.hpp>
#include <iostream>
int main()
{
double x = 5.0;
std::cout << boost::str(boost::format("%.2f") % x) << '\n';
}
std::ostringstream
。 boost::lexical_cast
适用于“简单格式”。std::string
get_formatted_value(double d) {
std::ostringstream oss;
oss.setprecision(3);
oss.setf(std::ostringstream::showpoint);
oss << d;
return oss.str();
}
你也可以使用sprintf,它比ostringstream更快。
#include <cstdio>
#include <string>
using namespace std;
int main()
{
double n = 5.0;
char str_tmp[50];
sprintf(str_tmp, "%.2f", n);
string number(str_tmp);
}
using namespace std;
。 - AnotherParker