### How to set a result to 2 decimal places

I'm only allowed to use the <iostream> library, so setprecision can't be used. How can I set 2 decimal places for the average?
 ``123`` `````` average = sum/(double)n; cout << "Average = "<
Last edited on
 ``12`` ``````int ipart = (int)(average * 100); average = ipart / 100.0;``````
//now has 2 decimal places. but it will still print zeros. If you want to get rid of the zeros you can either

convert it to text and take a substring, find the decimal point and take 2 more characters.

or do a messy decimal to 2 integer + custom print statement (let me know if you want this one).

I thought fmod might offer a cool answer but maybe not (anyone?).

also try this gem:
`cout << average << "\b\b\b" << " " << endl;` //back up 3 characters and overwrite with 3 spaces...
Last edited on
Er,

 ``1234`` ``````double pi = 3.1415926; std::cout << "whole part: " << (int)pi << "\n"; std::cout << "fractional part: " << (int)((pi - (int)pi) * 100) << "\n";`````` ```while part: 3 fractional part: 14```

Make yourself a function.

 ``1234567891011121314`` ``````#include std::ostream& print( std::ostream& outs, double x ) { return outs << (int)x << "." << (int)((x - (int)x) * 100); } int main() { double pi = 3.1415926; print( std::cout, pi ) << "\n"; }``````

 ``1234567891011121314151617181920`` ``````#include struct myprec2 { double x; myprec2( double x ): x(x) { } }; std::ostream& operator << ( std::ostream& outs, const myprec2& p ) { return outs << (int)p.x << "." << (int)((p.x - (int)p.x) * 100); } int main() { double pi = 3.1415926; std::cout << myprec2( pi ) << "\n"; }``````

Etc.

I forgot something important -- leading zeros. See below.
Last edited on
I started to do a simpler version of that but
100.01
becomes
100 and 1 integer parts
and prints 100.1

so you have to handle that aggravation.
I think all you need is
if ( (int)val - val < 10)
cout <<'0' ; //insert extra zero padding.
Last edited on
LOL, you're right. (I was half asleep when I wrote that above.)

 ``12345`` ``````int frac = (x - (int)x) * 100; std::cout << (int)x; if (frac < 10) std::cout << "0"; std::cout << frac;``````

Thanks jonnin!
Topic archived. No new replies allowed.