如何在C++中使用boost::lexical_cast将双精度数转换为字符串?

14

我想使用 lexical_cast 把浮点数转换成字符串。通常情况下这个函数能够正常工作,但是如果数字没有小数点,就会出现问题。我该怎么样才能控制在字符串中显示的小数位数呢?

例如:

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

结果编号为 5,我需要数字5.00

4个回答

31

根据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;
}

16

看看 boost::format 库。它把 printf 的易用性和流的类型安全结合起来。至于速度,我不确定,但我认为现在并不重要。

#include <boost/format.hpp>
#include <iostream>

int main()
{
   double x = 5.0;
   std::cout << boost::str(boost::format("%.2f") % x) << '\n';
}

3
如果您需要复杂的格式,请使用std::ostringstreamboost::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();
}

1

你也可以使用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);
}

3
我想你是指snprintf :) - criddell
3
不要使用using namespace std; - AnotherParker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接