fix: unbounded_percentage always rounded down

For example if lower / upper = 0.019 (1.9%), it would return 1% instead
of 2%

Fixes #2399
This commit is contained in:
patrick96 2021-03-03 22:38:05 +01:00 committed by Patrick Ziegler
parent 2fd6d20999
commit 93ab639c8a
3 changed files with 17 additions and 10 deletions

View File

@ -109,6 +109,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([`#2292`](https://github.com/polybar/polybar/issues/2292))
- Parser error if click command contained `}`
([`#2040`](https://github.com/polybar/polybar/issues/2040))
- Slight imprecision when calculating percentages. This caused the volume
reported by alsa to be off by one.
([`#2399`](https://github.com/polybar/polybar/issues/2399))
- `internal/backlight`: With amdgpu backlights, the brightness indicator was slightly behind.
([`#2367](https://github.com/polybar/polybar/issues/2367))

View File

@ -1,6 +1,7 @@
#pragma once
#include <algorithm>
#include <cmath>
#include "common.hpp"
@ -37,15 +38,17 @@ namespace math_util {
* Calculate the percentage for a value
* between min_value and max_value
*/
template<typename ValueType, typename ReturnType = int>
ReturnType unbounded_percentage(ValueType value, ValueType min_value, ValueType max_value){
template <typename ValueType, typename ReturnType = int>
ReturnType unbounded_percentage(ValueType value, ValueType min_value, ValueType max_value) {
auto upper = (max_value - min_value);
auto lower = static_cast<float>(value - min_value);
ValueType percentage = (lower / upper) * 100.0f;
if (std::is_integral<ReturnType>())
percentage += 0.5f;
float percentage = (lower / upper) * 100.0f;
if (std::is_integral<ReturnType>()) {
return static_cast<ReturnType>(std::round(percentage));
} else {
return percentage;
}
}
/**
* Calculates percentage for a value and
@ -113,6 +116,6 @@ namespace math_util {
inline int ceil(double value, int step = 1) {
return static_cast<int>((value * 10 + step * 10 - 1) / (step * 10)) * step;
}
}
} // namespace math_util
POLYBAR_NS_END

View File

@ -1,6 +1,7 @@
#include "common/test.hpp"
#include "utils/math.hpp"
#include "common/test.hpp"
using namespace polybar;
TEST(Math, min) {
@ -38,7 +39,7 @@ TEST(Math, percentage) {
EXPECT_EQ(55.0f, (math_util::percentage<float, float>(5.5f, 0.0f, 10.0f)));
EXPECT_EQ(56, (math_util::percentage<float, int>(5.55f, 0.0f, 10.0f)));
EXPECT_EQ(43.75f, (math_util::percentage<float, float>(5.25f, 0.0f, 12.0f)));
EXPECT_EQ(41, (math_util::percentage<int, int>(5, 0, 12)));
EXPECT_EQ(42, (math_util::percentage<int, int>(5, 0, 12)));
EXPECT_EQ(20.5f, (math_util::percentage<float, float>(20.5f, 0.0f, 100.0f)));
EXPECT_EQ(70.0f, (math_util::percentage<float, float>(4.5f, 1.0f, 6.0f)));
EXPECT_EQ(21, (math_util::percentage<float, int>(20.5f, 0.0f, 100.0f)));