Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

c++ - How to stop doubles converting to scientific notation when using a stringstream

I'm making a function to return the number of decimal and whole number digits and am converting the inserted typename number to a string using sstreams.

However the number when being converted to a string comes out in scientific notations which is not useful for counting the number of digits are in the normal number. How can I stop this from happening in my function below?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use std::fixed stream manipulator as:

ss << fixed << numb;

--

Example,

#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 << '' << b << '' << c << endl;
  cout <<   fixed    << a << '' << b << '' << c << endl;
  cout << scientific << a << '' << b << '' << c << endl;
  return 0;
}

Output:

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

Example is taken from here.

And you can use std::stringstream instead of cout, but the result would be same. Experiment it here:

http://www.ideone.com/HUrRw


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...