quick help with double

Started by
3 comments, last by VincentLascaux 19 years, 7 months ago
not new but freshening up on my c++ when using a double, how do you tell the computer you only want 2 decimal places? Example "You made 143.234485 dollars yesterday" vs. "You made 143.23 dollars yesterday"
Larry CharlesCentra Entertainment Studios
Advertisement
#include <iostream>using namespace std;int main(int argc, char* argv[]) {        cout.setf(ios::fixed); // use a fixed number of decimals. 	cout.precision(2); //make it 2 decimal places	cout << 0.444444;        return 0;}
Thanks, thats what i needed.
Larry CharlesCentra Entertainment Studios
or have a look at iomanipulators (see the setw example)
You should not use double to do that kind of thing
Store the amount in cents

One could write a decimal class

template<int nbDecimals, class Int = int, int base=10>class Decimal{public: Decimal(Int i): value(i*decalage) { } Decimal(Int i, Int d) : value(i*decalage+d) { assert(d>=0 && d<decalage); } //Define all the operators (=, +, *...)private: Int value; static const Int decalage = Power<base, nbDecimals>::value;}template<int v, int n>struct Power{ static const int value = Power<v, n-1>::value * v;}template<int v>struct Power<v, 0>{ static const int value = 1;}

This topic is closed to new replies.

Advertisement