float << operation by setting the precision for both integer part and float part
I would like to print floating point numbers in a format like this.
01234.56
I use the following function to round a float to n digits.
double round(double val, int precision)
{
std::stringstream s;
s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
s >> val;
return val;
}
A开发者_StackOverflow社区nd the following line to output any number with leading zeroes to a fixed length.
setfill ('0') << setw(5) << number
But when I try to combine the two, I end up with non-consistent length, like in the following examples:
8.2 => 008.2
4.57 => 04.56
What I would like to have is an output like this:
8.2 => 08.20
4.57 => 04.57
Can you show me a function like string myround (double d, intpart n, floatpart f)
which returns:
myround (1234.5, 5, 2) => 01234.50
myround (1234.569, 5, 2) => 01234.57
I imageine it has been asked before, but I couldn't find it using the internal search engine.
the fixed manipulator will do the trick I think, my example below outputs what you wanted:
#include <iostream>
#include <iomanip>
using namespace std;
int main(void) {
cout << setprecision(2) << setfill ('0') << setw(5) << fixed << 8.2 << endl;
cout << setprecision(2) << setfill ('0') << setw(5) << fixed << 4.57 << endl;
}
just put it into your stringstream and it should work. However, the fixed information will be lost when the string is converted to a double value again. I think it is no good idea to round a float using a string method.
精彩评论