Boost logo

Boost :

From: Tom Brinkman (reportbase_at_[hidden])
Date: 2008-05-30 18:29:45


Here are a few small utility functions that I use for rounding and
truncating values. Its probably a good idea to add this
functionality to boost. However, I'm sure that the implentations
could be significantly improved.

enum RoundDirection
{
  rd_AwayZero=0,
  rd_TowardZero=1,
};

template <class A> inline
A roundTo(A val, int decimalPlaces)
{
  double mult=pow(10.0, decimalPlaces);
  return round(val*mult)/mult;
}

template <class A> inline
A roundTo(A val, int decimalPlaces, RoundDirection rd)
{
        A ret;
        double mult=pow(10.0, decimalPlaces);
        bool less0=(val<0.0 ? true : false);

        if (less0)
        {
                if (rd==rd_AwayZero)
                        rd=rd_TowardZero;
                else if (rd==rd_TowardZero)
                        rd=rd_AwayZero;
        }

        switch (rd)
        {
                case rd_AwayZero:
                        ret=ceil(val*mult)/mult;
                        break;
                case rd_TowardZero:
                        ret=floor(val*mult)/mult;
         }
        
        return ret;
}

template <class A> inline
A truncTo(A val, int decimalPlaces)
{
        double mult=pow(10.0, decimalPlaces);
        return trunc(val*mult)/mult;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk