Boost logo

Boost Users :

From: Fernando Cacciola (fernando.cacciola_at_[hidden])
Date: 2008-04-23 09:17:01


Hi Rainer,

Sorry I just saw this.

> Hi all,
>
> I just discovered (by debugging instead of reading :-() that a
> numeric_cast from a floating to an integral type always truncates by
> default, that is, 26.99999 is casted to 26.
> Is there a way to tell numeric_cast to use the nearest integer?
> Of course I can add 0.5 to my value and cast afterwards but that's
> definitely ugly.
>

numeric_cast<> uses the default policies, but you an easily create you own
version with any other policy, like the one which rounds floats to the
nearest integer: RoundEven<>

#include <boost/numeric/conversion/converter.hpp>

template<typename Target, typename Source>
inline
Target my_numeric_cast ( Source arg )
{
  typedef boost::numeric::conversion_traits<Target,Source> Traits ;

  typedef
boost::numeric::converter<Target,Source,Traits,boost::numeric::def_overflow_handler,boost::numeric::RoundEven<Source>
> Converter ;

  return Converter::convert(arg);
}

HTH

-- 
Fernando Cacciola
SciSoft
http://scisoft-consulting.com
http://fcacciola.50webs.com
http://groups.google.com/group/cppba

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net