Skip to content

Commit a4cf4c3

Browse files
authored
Merge pull request #487 from OpenVicProject/fixed_point_round_to_int
Round fixed_point_t to int away from zero
2 parents 931844a + 5ecdfd2 commit a4cf4c3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/openvic-simulation/types/fixed_point/FixedPoint.hpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,19 @@ namespace OpenVic {
200200
return static_cast<int32_t>(to_int64_t());
201201
}
202202

203+
//away from zero
204+
constexpr int64_t to_int64_t_rounded() const {
205+
const fixed_point_t fp = *this;
206+
if (fp >= 0) {
207+
return (fp + _0_50).value >> PRECISION;
208+
} else {
209+
return (fp - _0_50).value >> PRECISION;
210+
}
211+
}
212+
constexpr int32_t to_int32_t_rounded() const {
213+
return static_cast<int32_t>(to_int64_t_rounded());
214+
}
215+
203216
template<std::integral T>
204217
constexpr T to() const {
205218
return static_cast<T>(to_int64_t());

tests/src/types/FixedPoint.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,20 @@ TEST_CASE("fixed_point_t Rounding methods", "[fixed_point_t][fixed_point_t-round
9999
CONSTEXPR_CHECK(_2_55.round_up_to_multiple(5) == 5);
100100
CONSTEXPR_CHECK(_2_55.round_down_to_multiple(fixed_point_t::_0_25) == 2.50_a);
101101
CONSTEXPR_CHECK(_2_55.round_up_to_multiple(fixed_point_t::_1_50) == 3);
102+
103+
CONSTEXPR_CHECK((fixed_point_t::_0_50 - fixed_point_t::epsilon).to_int32_t_rounded() == 0);
104+
CONSTEXPR_CHECK(fixed_point_t::_0_50.to_int32_t_rounded() == 1);
105+
CONSTEXPR_CHECK((-fixed_point_t::_0_50).to_int32_t_rounded() == -1);
106+
CONSTEXPR_CHECK(fixed_point_t::_1_50.to_int32_t_rounded() == 2);
107+
CONSTEXPR_CHECK((-fixed_point_t::_1_50).to_int32_t_rounded() == -2);
108+
CONSTEXPR_CHECK(_2_55.to_int32_t_rounded() == 3);
109+
110+
CONSTEXPR_CHECK((fixed_point_t::_0_50 - fixed_point_t::epsilon).to_int64_t_rounded() == 0);
111+
CONSTEXPR_CHECK(fixed_point_t::_0_50.to_int64_t_rounded() == 1);
112+
CONSTEXPR_CHECK((-fixed_point_t::_0_50).to_int64_t_rounded() == -1);
113+
CONSTEXPR_CHECK(fixed_point_t::_1_50.to_int64_t_rounded() == 2);
114+
CONSTEXPR_CHECK((-fixed_point_t::_1_50).to_int64_t_rounded() == -2);
115+
CONSTEXPR_CHECK(_2_55.to_int64_t_rounded() == 3);
102116
}
103117

104118
TEST_CASE("fixed_point_t Parse methods", "[fixed_point_t][fixed_point_t-parse]") {

0 commit comments

Comments
 (0)