Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth.
Or is there another way to do it?
Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth.
Or is there another way to do it?
You actually don't need Boost at all, just the C library included in the C++ library. Specifically, you need to include the cmath header:
Round up a number: ceil(): http://www.cplusplus.com/reference/clibrary/cmath/ceil/
Round down a number: floor(): http://www.cplusplus.com/reference/clibrary/cmath/floor/
You can write your own round function then:
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>
double roundFloat(double x)
{
double base = floor( x );
if ( x > ( base + 0.5 ) )
return ceil( x );
else return base;
}
int main()
{
std::string strInput;
double input;
printf( "Type a number: " );
std::getline( std::cin, strInput );
input = std::atof( strInput.c_str() );
printf( "\nRounded value is: %7.2f\n", roundFloat( input ) );
return EXIT_SUCCESS;
}
You can use lround
available in C99.
#include <cmath>
#include <iostream>
int main() {
cout << lround(1.4) << "\n";
cout << lround(1.5) << "\n";
cout << lround(1.6) << "\n";
}
(outputs 1, 2, 2).
Check your compiler documentation if and/or how you need to enable C99 support.