Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   limiting decimal places (http://www.programmingforums.org/showthread.php?t=15207)

aShoe Feb 18th, 2008 6:58 PM

limiting decimal places
 
Can some one give me an idea of how to limit decimal spaces from a double.

dr.p Feb 18th, 2008 8:02 PM

Re: limiting decimal places
 
aShoe, if you're using the iostream library for output, you need to use the setprecision() manipulator (http://cppreference.com/io_flags.html#manipulators).

Example:
:

#include <iostream>
#include <iomanip>
//...
float floatval = 4.026783;
std::cout << std::dec << std::setprecision(3) << floatval << std::endl;
// outputs "4.03"


Or, if you're using C style output:
:

#include <stdio.h>
//...
float floatval = 4.026783;
printf("%.2f\n", nfloat);
// outputs "4.03"


Ancient Dragon Feb 18th, 2008 8:05 PM

Re: limiting decimal places
 
You can only limit them on output, such as with cout of another output stream
:

double x = 12.1234567890;
cout << setprecision(4) << width(4) << x << "\n";


has the following output
:

12.12
Press any key to continue . . .


[edit] I was too slow. what dr.p said[/edit]


All times are GMT -5. The time now is 3:35 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC