小编Ser*_*nov的帖子

如何以用户友好的形式将'double'转换为'string'

我有以下问题:客户希望以最佳方式呈现double类型string.它需要转换为字符串并显示在表单(短信,表格和其他)上.

100000000.949999 needs to be converted in 100000000.950;
10.000000001 -> 10.0;
100000000000000.19292 -> 1e+14;
1000.123456789 -> 1000.123;
0.00001 -> 0.0;
Run Code Online (Sandbox Code Playgroud)

转换代码是性能关键,它意味着不应该使用std::stringstream+ setprecision().

将params'precision'作为我的toStringNew()函数的参数实现会很棒,但是这些改进可能会严重影响我们的所有系统,我们计划在下一个版本中实现它.但这个问题现在已经存在.
我写了以下代码:

inline bool toStringNew(std::string& str, double const& value)
{
    static const char *zero_double_str = "0.0";
    static const double zero_double_limit = 0.001;
    static const int max_double_prec_symbol = 13;
    static const int max_fract_num = 3;
    static const int max_fract_mul = pow(10, max_fract_num);
    str.clear();
    //get digits of integer part
    double fabs_value …
Run Code Online (Sandbox Code Playgroud)

c++ string double

12
推荐指数
2
解决办法
355
查看次数

标签 统计

c++ ×1

double ×1

string ×1