C++ 如何在使用stringstream时阻止双精度转换为科学记数法
我正在创建一个函数来返回十进制和整数位数,并使用C++ 如何在使用stringstream时阻止双精度转换为科学记数法,c++,stringstream,scientific-notation,C++,Stringstream,Scientific Notation,我正在创建一个函数来返回十进制和整数位数,并使用sstreams将插入的typenamenumber转换为字符串 然而,当转换成字符串时,数字以科学的符号表示,这对于计算数字是不有用的。数字是正常的数字。我怎样才能在下面的函数中阻止这种情况发生 enum { DECIMALS = 10, WHOLE_NUMBS = 20, ALL = 30 }; template < typename T > int Numbs_Digits(T numb, int scope) { st
sstream
s将插入的typename
number转换为字符串
然而,当转换成字符串时,数字以科学的符号表示,这对于计算数字是不有用的。数字是正常的数字。我怎样才能在下面的函数中阻止这种情况发生
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;
}
enum{DECIMALS=10,整数=20,ALL=30};
模板int Numbs\u数字(T numb,int范围)
{
stringstream ss(stringstream::in | stringstream::out);
stringstream ss2(stringstream::in | stringstream::out);
无符号长整型长度=0;
无符号长整型;
ss2将流操纵器用作:
ss << fixed << numb;
这一例子取自
您可以使用std::stringstream
代替cout
,但结果是一样的。在这里进行实验:
您需要使用来格式化您想要的字符串。在您的情况下,您可能需要使用fixed
format标志:
ss << std::fixed << numb;
ss << std::scientific << numb;
在发布代码时,请只发布一个最小的工作示例。这太多了。在使用时,ostream中可能会重复Prevent scientific notation(防止科学记数法)?是否有任何方法可以防止“修复”我也不希望2006变为2006.00000,因为它会在字符串=p中添加不必要的“0”字符,但是谢谢!@Griffin:这个例子也使用了如何做到这一点。使用精度(5)
。
ss << std::fixed << numb;
ss << std::scientific << numb;