I’m trying to convert a double number to a std::string, the conversion should print either in the decimal format with 2 decimal digits or in the exponential form:
- 1 -> 1.00
- 0.1 -> 0.10
- 0.01 -> 0.01
- 0.015 -> 1.5e-2
- 10 -> 10.00
- 100 -> 100.00
- 15000 -> 1.5e4
I tried to use the boost::format function with the %g type, but while it is possible to set the number of significant digits, it’s not possible to set the number of printed digits after the decimal point:
- 1 -> 1
- 0.1 -> 0.1
- 0.01 -> 0.01
- 10 -> 10
- 100 -> 100
Is there a better way of doing this kind of conversion/formatting? I would preferably use the Standard Library or Boost.
Choose
scientificorfixeddepending on the size of the number.It’s that easy.
Cheers & hth.,