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 sstream
s.
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;
}
You need to write: std::cout << fixed; std::cout << setprecision(2) << f; fixed disables the scientific notation i.e. 1.23e+006 and fixed is a sticky manipulator so you need to disable it if you want to revert back to scientific notation.
(1) Right-click a cell where you want to remove scientific notation, and (2) choose Format Cells… 2. In the Format Cells window, (1) select the Number category, (2) set the number of decimal places to 0, and (3) click OK. Now the scientific notation is removed.
(For example, to decrease the exponent by 3, subtract 3 from the exponent and move the decimal point in the mantissa three times to the right). 2. When all numbers in scientific notation have powers with the same exponent, add or subtract the mantissa(s). Keep the power the same.
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 << '\t' << b << '\t' << c << endl;
cout << fixed << a << '\t' << b << '\t' << c << endl;
cout << scientific << a << '\t' << b << '\t' << 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With