CMathUtils::roundToMultipleOf

refs #556
This commit is contained in:
Roland Winklmeier
2016-01-14 00:30:14 +01:00
parent ab2e5af8d6
commit b3d45f58e6
5 changed files with 96 additions and 0 deletions

View File

@@ -93,5 +93,21 @@ namespace BlackMisc
return r % ((high + 1) - low) + low;
}
int CMathUtils::roundToMultipleOf(int value, int divisor)
{
Q_ASSERT(divisor != 0);
Q_ASSERT(divisor >= - std::numeric_limits<int>::max());
divisor = std::abs(divisor);
Q_ASSERT(std::abs(value) < std::numeric_limits<int>::max() - divisor / 2);
int multiplier = value / divisor;
int remainder = std::abs(value % divisor);
int shortfall = divisor - remainder;
if (shortfall < remainder) { multiplier += value < 0 ? -1 : 1; }
return multiplier * divisor;
}
} // namespace
} // namespace

View File

@@ -101,6 +101,9 @@ namespace BlackMisc
//! Random number between low and high
static int randomInteger(int low, int high);
//! Round numToRound to the nearest multiple of multiple
static int roundToMultipleOf(int value, int divisor);
};
} // namespace