如何在使用字符串流时停止双精度转换为科学记数法

时间:2011-05-15 19:54:59

标签: c++ stringstream scientific-notation

我正在创建一个函数来返回十进制和整数位数,并使用typename s将插入的sstream数字转换为字符串。

然而,转换为字符串时的数字以科学计数法出现,这对于计算正常数字中的位数无效。我怎样才能阻止这种情况发生在下面的函数中?

enum { DECIMALS = 10, WHOLE_NUMBS = 20, ALL = 30 };

template < typename T > int Numbs_Digits(T numb, int scope)
{
    stringstream ss(stringstream::in | stringstream::out);
    stringstream ss2(stringstream::in | stringstream::out);
    unsigned long int length = 0;
    unsigned long int numb_wholes;

    ss2 << (int) numb;
    numb_wholes = ss2.str().length();
    ss2.flush();
    bool all = false;

    switch (scope) {
    case ALL:
        all = true;

    case DECIMALS:
        ss << numb;
        length += ss.str().length() - (numb_wholes + 1);  // +1 for the "."
        if (all != true)
            break;

    case WHOLE_NUMBS:
        length += numb_wholes;
        if (all != true)
            break;

    default:
        break;
    }
    return length;
}

2 个答案:

答案 0 :(得分:27)

使用std::fixed流操作符:

ss << fixed << numb;

-

实施例,

#include <iostream>
using namespace std;

int main () {
  double a,b,c;
  a = 3.1415926534;
  b = 2006.0;
  c = 1.0e-10;
  cout.precision(5);
  cout       <<         a << '\t' << b << '\t' << c << endl;
  cout <<   fixed    << a << '\t' << b << '\t' << c << endl;
  cout << scientific << a << '\t' << b << '\t' << c << endl;
  return 0;
}

输出:

3.1416          2006            1e-010
3.14159         2006.00000      0.00000
3.14159e+000    2.00600e+003    1.00000e-010

示例取自here

您可以使用std::stringstream代替cout,但结果会相同。在这里试验:

http://www.ideone.com/HUrRw

答案 1 :(得分:8)

您需要使用stream manipulators根据需要格式化字符串。在您的情况下,您可能希望使用fixed格式标志:

ss << std::fixed << numb;

相反(如果你想要强制科学记数法)是scientific格式标志:

ss << std::scientific << numb;