使用stringstream时如何停止将double转换为科学计数法 [英] How to stop doubles converting to scientific notation when using a stringstream

查看:624
本文介绍了使用stringstream时如何停止将double转换为科学计数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一个函数以返回小数位数和整数位数,并使用 sstream将插入的 typename 数字转换为字符串 s。

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;
}


推荐答案

使用 std :: fixed 流操纵器为:

Use std::fixed stream manipulator as:

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

示例取自这里

您可以使用 std :: stringstream 代替 cout ,但结果将相同。在此处进行实验:

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

http://www.ideone。 com / HUrRw

这篇关于使用stringstream时如何停止将double转换为科学计数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆