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;
    std::ostringstream out;
    out << std::fixed << 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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值