Saturday, May 22, 2010

C++ show decimal places of int?

How can I show 2 decimal places of a variable that is an integer?


For example:





int money


cin %26gt;%26gt; money (54)


cout %26lt;%26lt; money (54.00)

C++ show decimal places of int?
Use ios_base::precision or setprecision() instead of printf(); the iostream methods (including stream manipulators) are far more efficient than the old C libraries where printf() is a legacy function.





// setprecision example


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


using namespace std;





int main () {


int money = 54;


cout %26lt;%26lt; fixed;


cout %26lt;%26lt; setprecision (2) %26lt;%26lt; money %26lt;%26lt; endl;


return 0;


}





-- or --





// modify precision


#include %26lt;iostream%26gt;


using namespace std;





int main () {


int money = 54;


cout.precision(2);


cout.setf(ios::fixed,ios::floatfield); // floatfield set to fixed


cout %26lt;%26lt; money %26lt;%26lt; endl;


return 0;


}
Reply:JUST REPLACE THE int BY float YOU MAY GET YOUR REQUIRED RESULT.
Reply:Firstly, an integer has no decimal places. Therefore, the easiest way to show 2 decimal places after an integer would be just to output the integer, followed by ".00"





If however, you wanted to force the output of 2 decimal places, using printf would be easier:





printf("%3.2d", money);
Reply:#include %26lt;iomanip%26gt;





I'll leave it to you to look it up and see what you can learn about it.





http://www.cplusplus.com is a good place to start.


No comments:

Post a Comment