Saturday, June 16, 2007

String formatting using C++

Say you need to create a special string that does shows floating point numbers.
Lets put another constraint , say you need to show upto K decimal places.

e.g u need an output like this
123.45 <--- 2 decimal places

say double d = 123.456

then u can create a string which shows upto 2 decimal places like this.

ostringstream o;
o.setf(ios::fixed);
o.precision(2);
o << d;
cout << o.str();

No comments: