DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   fixed number of decimals (http://www.daniweb.com/forums/thread110458.html)

sgw Feb 22nd, 2008 10:35 pm
fixed number of decimals
 
Hi,

If I want to print several numbers, say 12.3, 24.038, 154.9181, 0.4778--anyway, just all kinds of numbers, how can I print all of them with fixed number of decimals, say two decimals, that is, the output will be: 12.30, 24.03, 154.91, 0.47... ? The "setprecision(...)" doesn't work because it specifies the number of "significant" digits, rather than the number of digits after the decimal point.

Thank you in advance!

henpecked1 Feb 22nd, 2008 10:46 pm
Re: fixed number of decimals
 
cout << fixed << setprecision (2);

try that

jesseb07 Feb 22nd, 2008 10:51 pm
Re: fixed number of decimals
 
(seeing as I can't delete a post, to prevent redundancy, I'll give an alternate solution)

Hi, in the case of setprecision() not working, try the following:

cout.setf(ios::fixed); // prevents e-notation
cout.setf(ios::showpoint); //always shows decimal point
cout.precision(2); // with 2 being the number of decimals

using that, here's what happened in my test program:

4 inputs
1.234
1.23
123.456
1234

and then just used cout to put them on the screen
1.23
1.23
123.46 // rounded
1234.00

See if that works for you

~J

sgw Feb 22nd, 2008 11:25 pm
Re: fixed number of decimals
 
Thank you both! Both work. The "fixed" is simpler to use. For the second way, is that it applies to all the cout statements after the statement?

jesseb07 Feb 23rd, 2008 1:25 am
Re: fixed number of decimals
 
Quote:

Originally Posted by sgw (Post 543125)
Thank you both! Both work. The "fixed" is simpler to use. For the second way, is that it applies to all the cout statements after the statement?

That is my understanding as well, however if I recall you can make exceptions but I may be wrong there.

~J


All times are GMT -4. The time now is 1:56 am.

Forum system based on vBulletin Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
©2003 - 2010 DaniWeb® LLC