views:

117

answers:

3

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?

+3  A: 
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
Forrest
+1  A: 

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;
}
Baltasarq
A: 

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.

honk