convert double to string with "to_string"

Dear friends:
I convert a double "1E-20" to a string with "to_string" function, but i only get "0.0000", how to resolve this problem.
Regards
With floating point types std::to_string may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.

http://en.cppreference.com/w/cpp/string/basic_string/to_string
std::to_string() may return zero for small floating point numbers
(results are similar to what std::printf() with a "%f" format specifier would have printed).

We can roll out one of our own:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <limits>
#include <sstream>
#include <iomanip>

namespace my {

    std::string to_string( double d ) {

        std::ostringstream stm ;
        stm << std::setprecision(std::numeric_limits<double>::digits10) << d ;
        return stm.str() ;
    }
}

int main() {

    const double d = 1.23456789e-50 ;
    std::cout << std::to_string(d) << '\n' // 0.000000
              << my::to_string(d) << "\n\n" ; // 1.23456789e-50

    const double d1 = -1.23456789e+20 ;
    std::cout << std::to_string(d1) << '\n' // -123456788999999995904.000000 (typical)
              << my::to_string(d1) << "\n\n" ; // -1.23456789e+20
}

http://coliru.stacked-crooked.com/a/3d4a91d472592a06
http://rextester.com/NJNI99535
Registered users can post here. Sign in or register to post.