Skip to content

Commit

Permalink
#67: edge case correction
Browse files Browse the repository at this point in the history
  • Loading branch information
vpiotr committed Sep 18, 2024
1 parent f61fd94 commit 8d9314d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
25 changes: 24 additions & 1 deletion include/decimal.h
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,30 @@ class dec_utils {
public:
// result = (value1 * value2) / divisor
inline static int64 multDiv(const int64 value1, const int64 value2,
int64 divisor) {
int64 divisor) {

if (value1 == 0 || value2 == 0) {
return 0;
}

if (divisor == 1) {
return value1 * value2;
}

if (value1 == 1) {
int64 result;
if (RoundPolicy::div_rounded(result, value2, divisor)) {
return result;
}
}

if (value2 == 1) {
int64 result;
if (RoundPolicy::div_rounded(result, value1, divisor)) {
return result;
}
}

// we don't check for division by zero, the caller should - the next line will throw.
const int64 value1int = value1 / divisor;
int64 value1dec = value1 % divisor;
Expand Down
18 changes: 18 additions & 0 deletions tests/decimalTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,24 @@ BOOST_AUTO_TEST_CASE(decimalAsInteger)
BOOST_CHECK_EQUAL(c.getAsInteger(), expectedValue);
}

BOOST_AUTO_TEST_CASE(issue67)
{
using namespace std;
dec::decimal<4, dec::half_even_round_policy> p1("350.68");
dec::decimal<4, dec::half_even_round_policy> p2("359.2050");

dec::decimal<0, dec::half_even_round_policy> s1("550");
dec::decimal<0, dec::half_even_round_policy> s2("550");

dec::decimal<0, dec::half_even_round_policy> s_sum = s1 + s2;
dec::decimal<4, dec::half_even_round_policy> p_sum = p1 + p2;
dec::decimal<4, dec::half_even_round_policy> result = (p_sum / s_sum);

dec::decimal<4, dec::half_even_round_policy> expected("0.6454");

BOOST_CHECK_EQUAL(expected, result);
}

// test with values internally > 2^32
BOOST_AUTO_TEST_CASE(decimalMidOverflow)
{
Expand Down

0 comments on commit 8d9314d

Please sign in to comment.