Sign in to follow this  
flip5577

quick help with double

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this