1 // Copyright John Maddock 2007.
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0. (See accompanying file
4 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 #ifndef BOOST_MATH_TRUNC_HPP
7 #define BOOST_MATH_TRUNC_HPP
13 #include <boost/math/tools/config.hpp>
14 #include <boost/math/policies/error_handling.hpp>
15 #include <boost/math/special_functions/fpclassify.hpp>
17 namespace boost{ namespace math{
19 template <class T, class Policy>
20 inline T trunc(const T& v, const Policy& pol)
23 if(!(boost::math::isfinite)(v))
24 return policies::raise_rounding_error("boost::math::trunc<%1%>(%1%)", 0, v, pol);
25 return (v >= 0) ? static_cast<T>(floor(v)) : static_cast<T>(ceil(v));
28 inline T trunc(const T& v)
30 return trunc(v, policies::policy<>());
33 // The following functions will not compile unless T has an
34 // implicit convertion to the integer types. For user-defined
35 // number types this will likely not be the case. In that case
36 // these functions should either be specialized for the UDT in
37 // question, or else overloads should be placed in the same
38 // namespace as the UDT: these will then be found via argument
39 // dependent lookup. See our concept archetypes for examples.
41 template <class T, class Policy>
42 inline int itrunc(const T& v, const Policy& pol)
45 T r = boost::math::trunc(v, pol);
46 if(fabs(r) > (std::numeric_limits<int>::max)())
47 return static_cast<int>(policies::raise_rounding_error("boost::math::itrunc<%1%>(%1%)", 0, v, pol));
48 return static_cast<int>(r);
51 inline int itrunc(const T& v)
53 return itrunc(v, policies::policy<>());
56 template <class T, class Policy>
57 inline long ltrunc(const T& v, const Policy& pol)
60 T r = boost::math::trunc(v, pol);
61 if(fabs(r) > (std::numeric_limits<long>::max)())
62 return static_cast<long>(policies::raise_rounding_error("boost::math::ltrunc<%1%>(%1%)", 0, v, pol));
63 return static_cast<long>(r);
66 inline long ltrunc(const T& v)
68 return ltrunc(v, policies::policy<>());
71 #ifdef BOOST_HAS_LONG_LONG
73 template <class T, class Policy>
74 inline boost::long_long_type lltrunc(const T& v, const Policy& pol)
77 T r = boost::math::trunc(v, pol);
78 if(fabs(r) > (std::numeric_limits<boost::long_long_type>::max)())
79 return static_cast<boost::long_long_type>(policies::raise_rounding_error("boost::math::lltrunc<%1%>(%1%)", 0, v, pol));
80 return static_cast<boost::long_long_type>(r);
83 inline boost::long_long_type lltrunc(const T& v)
85 return lltrunc(v, policies::policy<>());
92 #endif // BOOST_MATH_TRUNC_HPP