1

I am looking for a good way to round an int in Qt to the nearest 5.

e.g:

8 -> 10  
12 -> 10  
13 -> 15  
15 -> 15  
17 -> 15

and so on

demonplus
  • 5,613
  • 12
  • 49
  • 68
MajorC
  • 21
  • 3
  • Possible duplicate of [C++: Rounding up to the nearest multiple of a number](http://stackoverflow.com/questions/3407012/c-rounding-up-to-the-nearest-multiple-of-a-number) – dtech Feb 14 '16 at 12:09

2 Answers2

2

Rounding in C++ to the nearest integer number usually is done via:

static_cast<int>(number + 0.5);

Now, to round it to the next 5, I would bring it into the system where we can apply this rounding rule (i.e. 5 -> 1, 6 -> 1.2) and then bring it back into the system where 5 really is 5:

int roundToNearestFive(int number)
{
    return static_cast<int>(number / 5. + .5) * 5;
}

I find this formulation easiest.

IceFire
  • 4,016
  • 2
  • 31
  • 51
1

Here a possible solution:

#include<iostream>

int toNearest5(int i) {
    int r = i%5, o = 0;

    if(r) {
        o = r/5. >= .5 ? 5 : 0;
    }

    return (i-r+o);
}

int main() {
    using namespace std;
    cout << toNearest5(8) << endl;
    cout << toNearest5(12) << endl;
    cout << toNearest5(13) << endl;
    cout << toNearest5(15) << endl;
    cout << toNearest5(17) << endl;
}

The idea is to get the number and round it to the lowest multiple of 5 (you can do that by removing the remainder), that is:

int remainder = i%5;
int rounded = i - remainder;

Now, you can check the remainder and add 5 to the rounded number if the remainder is greater than 2.5, otherwise add 0.
In order to check it, I've divided the remainder by 5 (its upper bound), so that to get a number in [0,1[ and check it with 0.5 to know how to round the original number.

It follows a more compact version of the same function:

int toNearest5(int i) {
    int j = i%5;
    return (i - j + (j/5. >= .5 ? 5 : 0));
}

I don't know if the Qt framework offers something similar out of the box, but it's a matter of an one line function, you can easily write it for yourself.

skypjack
  • 49,335
  • 19
  • 95
  • 187