"Brandon" <bc******@creighton.edu> wrote in message
news:24**************************@posting.google.c om...
In a program, I'm using an ostringstream to convert a floating point
value to a string. When the numbers are big enough, they are
converted using scientific notation. To fix this, I changed the code
to
oStream << fixed << myFloat;
but now there are an unnecessary amount of trailing zeros that I don't
want. I seem to recall something in C, using printf(), where you
could specify how many places you wanted. For examples, using
something like printf("%1.2", 0.45678) would print the text "0.45".
Is there any way to force a certain number of decimal places in C++
using ios streams (ostringstreams in particular)?
I think you might be searching for std::setprecision() (<iomanip>) or
std::ios_base::precision().
int main() {
double testData[] = {0.00000001, 1.0, 20.0, 1000000000000000.0,
std::numeric_limits<double>::max()};
int numElems = sizeof(testData)/sizeof(testData[0]);
for ( int i = 0; i < numElems; ++i ) {
std::cout << testData[i] << std::endl;
}
std::cout << std::fixed << std::setprecision(2);
std::cout << "After modifying stream:" << std::endl;
for ( int i = 0; i < numElems; ++i ) {
std::cout << testData[i] << std::endl;
}
return 0;
}
Output (Win2K, VC++. Net 2003):
1e-008
1
20
1e+015
1.79769e+308
After modifying stream:
0.00
1.00
20.00
1000000000000000.00
17976931348623180000000000000000000000000000000000 00000000000000000000000000
0000
00000000000000000000000000000000000000000000000000 00000000000000000000000000
0000
00000000000000000000000000000000000000000000000000 00000000000000000000000000
0000
00000000000000000000000000000000000000000000000000 0000000000000000000.00
--
David Hilsee