C++ – Conversion of float numbers to a formatted string

boostcformattingprintf

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 -> 1.00
  2. 0.1 -> 0.10
  3. 0.01 -> 0.01
  4. 0.015 -> 1.5e-2
  5. 10 -> 10.00
  6. 100 -> 100.00
  7. 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 -> 1
  2. 0.1 -> 0.1
  3. 0.01 -> 0.01
  4. 10 -> 10
  5. 100 -> 100

Is there a better way of doing this kind of conversion/formatting? I would preferably use the Standard Library or Boost.

Best Answer

Choose scientific or fixed depending on the size of the number.

It's that easy.

Cheers & hth.,

Related Topic