c++floating-pointdoublec++14tostring

How to avoid `std::to_string()` making a very small double number to 0?


I have a requirement to store very small double numbers into a string format and then later reverse them. However, when I try to run std::to_string() on a small number like 4.7816457028269855e-143 then it simply makes it 0.

I referred Set precision of std::to_string when converting floating point values and its linked duplicate. But will setting the precision to a very large number solve this issue in all the platforms?

How to fix this issue?
Using any alternatives to to_string() is fine.


Solution

  • No, the problem is not precision, but the format. You want to print in scientific format (with exponent) but std::to_string() uses the fixed format by default and I'm not aware of any way to change this.

    However, streams use scientific if appropriate or you can force it with std::scientific:

    std::ostringstream oss;
    oss << 4.7816457028269855e-143;
    std::string numberAsString = oss.str(); // stores "4.78165e-143"  
    

    Of course you can increae the precision in addition to this.

    If for whatever reason you don't want to use scientific format, you can use the fixed format with a high enough precision. "High enough" meaning more than 142 in this case, because there will be 142 leading zeroes:

    oss << std::fixed << std::setprecision(142 + x);
    

    But the scientific format is better suited, I guess.