Reputation: 1
after searching an answer to my problem I decide to ask.
I was told I need to round the value of double into 3 decimal places.
I need to use this :
os.setf(std::ios::fixed,std::ios::floatfield);
os.precision(3);
so I am understand I need to create an object of type ostream so I wrote this:
ostream os;
os.setf(std::ios::fixed,std::ios::floatfield);
os.precision(3);
double a = 3.12364;
os << a;
but there is a compilation error so I changed the first row into :
ostream os(NULL);
then the compiler shut up, but I know it did not do anything. so how do I round the value using ostream ?
pay attention I do not want to print. I do not need/want to use cout
Upvotes: 0
Views: 640
Reputation: 137810
Assuming you want to put the double into a std::string
, use std::ostringstream
(which is derived from std::ostream
).
ostringstream os;
os.setf(std::ios::fixed,std::ios::floatfield);
os.precision(3);
double a = 3.12364;
os << a;
std::string rounded( os.str() ); // get the result
If you want to round it mathematically, then do
round( a * 1000 ) / 1000
Using a string in the middle of an equation is always a red flag ;v) .
Upvotes: 1
Reputation: 153919
First: if you need to use ostream
, you don't want to round the
value of a double to three decimal places, you want to display
the value with three decimal places. (To round it, you'd use
round( value * 100 ) / 100
.) Second, you usually don't use an
ostream
object, you use an object of a type derived from
ostream
: usually an ofstream
or ostringstream
.
The question is where you want this rounded value to appear. If
you need it in a file, then you will use ofstream
; if you want
it in a string (e.g. to place in a window component), it's
ostringstream
, and if you just want it to appear on standard
out, just output it to cout
(which is of a type derived from
ostream
).
Also, don't forget to restore the flags and the precision when
you're done: setf
and precision
make permanent changes to
the underlying stream.
Upvotes: 0
Reputation: 11025
If you do not really want to save the result in a string, you could use plain mathematics.
#include <cmath>
float myRound(float input) {
return input > 0
? floor(input * 1000 + 0.5) / 1000
: ceil(input * 1000 + 0.5) / 1000;
}
Be aware though, that the result will be incorrect if the multiplication by 1000 causes an overflow. In C++11, you can also make use of std::round
.
Upvotes: 1