Last active
August 29, 2015 14:12
-
-
Save beached/4eb0f7dd300a59b87057 to your computer and use it in GitHub Desktop.
Some useful little functions to round, ceil, and floor to the nearest N. A little rough, but they work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<class T, class U> | |
T round_by( T const & value, U const & rnd_by ) { | |
static_assert(std::is_arithmetic<T>::value, "First template parameter must be an arithmetic type"); | |
static_assert(std::is_floating_point<U>::value, "Second template parameter must be a floating point type"); | |
const auto rnd = round( static_cast<U>(value) / rnd_by ); | |
const auto ret = rnd*rnd_by; | |
return static_cast<T>(ret); | |
} | |
template<class T, class U> | |
T floor_by( T const & value, U const & rnd_by ) { | |
static_assert(std::is_arithmetic<T>::value, "First template parameter must be an arithmetic type"); | |
static_assert(std::is_floating_point<U>::value, "Second template parameter must be a floating point type"); | |
const auto rnd = floor( static_cast<U>(value) / rnd_by ); | |
const auto ret = rnd*rnd_by; | |
assert( ret <= value );// , __func__": Error, return value should always be less than or equal to value supplied" ); | |
return static_cast<T>(ret); | |
} | |
template<class T, class U> | |
T ceil_by( T const & value, U const & rnd_by ) { | |
static_assert(std::is_arithmetic<T>::value, "First template parameter must be an arithmetic type"); | |
static_assert(std::is_floating_point<U>::value, "Second template parameter must be a floating point type"); | |
const auto rnd = ceil( static_cast<U>(value) / rnd_by ); | |
const auto ret = rnd*rnd_by; | |
assert( ret >= value ); // , __func__": Error, return value should always be greater than or equal to value supplied" ); | |
return static_cast<T>(ret); | |
} | |
int main( int, char** ) { | |
std::cout << "36 rounded by 5 = " << round_by( 36, 5.0 ) << "\n"; // Will output 35 | |
std::cout << "36 ceil by 5 = " << ceil_by( 36, 5.0 ) << "\n"; // Will output 40 | |
std::cout << "36 floor by 5 = " << floor_by( 36, 5.0 ) << "\n"; // Will output 35 | |
std::cout << "36 rounded by 3.3 = " << round_by( 36, 3.3 ) << "\n"; // Will output 36.3 | |
std::cout << "86 2/3 rounded by 0.25 = " << round_by( 86.0+2.0*(1.0/3.0), 0.25 ) << "\n"; // Will output 86.75 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment