Monday, July 27, 2009

In C++, how do i display a float or a double to 2 decimal points?

I know that i can use printf() and %2.2f and stuff like that i learned in C, but is there a special way to do so in C++, where I'd use cout %26lt;%26lt; [number displayed to 2 decimal places] %26lt;%26lt; endl; ?

In C++, how do i display a float or a double to 2 decimal points?
cout %26lt;%26lt; fixed %26lt;%26lt; showpoint %26lt;%26lt; setprecision(2);





then have your cout statement for what you want displayed.





ie:


say . . . x=12.496


cout %26lt;%26lt; fixed %26lt;%26lt; showpoint %26lt;%26lt; setprecision(2) %26lt;%26lt; endl;


cout %26lt;%26lt; x %26lt;%26lt; endl;





this should display 12.49





you can also do it in one statement.


cout %26lt;%26lt; fixed %26lt;%26lt; showpoint %26lt;%26lt; setprecision(2) %26lt;%26lt; x %26lt;%26lt; endl;
Reply:use setprecision as given here http://www.cplusplus.com/reference/iostr...

hawthorn

No comments:

Post a Comment