开发者

Conversion of float numbers to a formatted string

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 开发者_StackOverflowform:

  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.


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

It's that easy.

Cheers & hth.,


No boost needed although there should be a way to do this with boost::format or sprintf if you want.

#include <iostream>
#include <iomanip>

int main()
{
    std::string numStr("3.14159265");
    double num(atof(numStr.c_str()));
    std::cout
        << std::setprecision(2) 
        << std::scientific << num
        << std::fixed << num;
    return 0;
}

Edit: Misread the question if you want to go from double to std::string I'd use a std::ostringstream which supports the same iostream manipulators and insertion operator. Then you can call str() to get a string out of it.


You can use ostringstream, like so

#include <sstream>
#include <string>

std::string FloatToString(float fNumber)
{
    std::ostringstream os;

    os << fNumber;

    return os.str();
}


I'm not sure if this is what you are looking for but... You can control the number of printed digits using cout with using the setprecision function.

#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
  double d = 123123.23234234;
  cout << setprecision(15) << d;
  system("pause");
  return 0;
}


sprintf() ; should be easy to help you print double into a string/char array .


Plain old C sprintf supports # of decimals like so: "%.3g"

You can turn the char* output into a std::string easily enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜