C++的to_string保留默认小数位的问题

        C++编译环境C++ 11,使用std::to_string函数将double转化成字符串发现小数位被做四舍五入,且保留6位小数,这个问题在实际使用过程中经常遇到,必须被坑过一次,才深深留意。也说明C++设计的一个瑕疵吧。那怎么解决这个问题呢?自己写一个转化函数,这里有一个示例供参考。

#include <sstream>
#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 6)
{
    int nn=n+1;
    std::ostringstream out;
    out << std::setprecision(nn) << a_value;
    return out.str();
}

int main()
{
    double d = 1.2345678956789;

    cout << "d=" << d << endl;

    string s = std::to_string(d);

    cout << "s=" << s << endl;

    cout << "to_string_with_precision后,d=" << to_string_with_precision(d, 10) << endl;

    return 0;
}

 如代码所示,其中,double类型的数据d在经cout输出后会保留5位小数,经函数std::to_string转化后保留6为小数;to_string_with_precision函数是实现控制精度转化成字符串函数,用到了std::ostringstream类型。

代码输出结果:

d=1.23457
s=1.234568
to_string_with_precision后,d=1.2345678957


版权声明:本文为dhp811原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。