• Advertisement
Sign in to follow this  

quick help with double

This topic is 4888 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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"

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement