Rounding, w/ unit test.

This commit is contained in:
JoelKatz
2013-02-01 16:47:08 -08:00
parent 9781c10736
commit 402f7539d4
2 changed files with 43 additions and 5 deletions

View File

@@ -1215,6 +1215,40 @@ std::string STAmount::getFullText() const
} }
} }
STAmount STAmount::getRound() const
{
if (mIsNative)
return *this;
uint64 valueDigits = mValue % 1000000000ull;
if (valueDigits == 1)
return STAmount(mCurrency, mIssuer, mValue - 1, mOffset, mIsNegative);
else if (valueDigits == 999999999ull)
return STAmount(mCurrency, mIssuer, mValue + 1, mOffset, mIsNegative);
return *this;
}
void STAmount::roundSelf()
{
if (mIsNative)
return;
uint64 valueDigits = mValue % 1000000000ull;
if (valueDigits == 1)
{
mValue -= 1;
if (mValue < cMinValue)
canonicalize();
}
else if (valueDigits == 999999999ull)
{
mValue += 1;
if (mValue > cMaxValue)
canonicalize();
}
}
#if 0 #if 0
std::string STAmount::getExtendedText() const std::string STAmount::getExtendedText() const
{ {
@@ -1461,7 +1495,7 @@ BOOST_AUTO_TEST_CASE( CustomCurrency_test )
BOOST_TEST_MESSAGE("Amount CC Complete"); BOOST_TEST_MESSAGE("Amount CC Complete");
} }
static void roundTest(int n, int d, int m) static bool roundTest(int n, int d, int m)
{ // check STAmount rounding { // check STAmount rounding
STAmount num(CURRENCY_ONE, ACCOUNT_ONE, n); STAmount num(CURRENCY_ONE, ACCOUNT_ONE, n);
STAmount den(CURRENCY_ONE, ACCOUNT_ONE, d); STAmount den(CURRENCY_ONE, ACCOUNT_ONE, d);
@@ -1470,18 +1504,19 @@ static void roundTest(int n, int d, int m)
STAmount res = STAmount::multiply(quot, mul, CURRENCY_ONE, ACCOUNT_ONE); STAmount res = STAmount::multiply(quot, mul, CURRENCY_ONE, ACCOUNT_ONE);
if (res.isNative()) if (res.isNative())
BOOST_FAIL("Product is native"); BOOST_FAIL("Product is native");
res.roundSelf();
cLog(lsDEBUG) << n << " / " << d << " = " << quot.getText();
STAmount cmp(CURRENCY_ONE, ACCOUNT_ONE, (n * m) / d); STAmount cmp(CURRENCY_ONE, ACCOUNT_ONE, (n * m) / d);
if (cmp.isNative()) if (cmp.isNative())
BOOST_FAIL("Comparison amount is native"); BOOST_FAIL("Comparison amount is native");
if (res == cmp) if (res == cmp)
return; return true;
cmp.throwComparable(res); cmp.throwComparable(res);
cLog(lsINFO) << "(" << num.getText() << "/" << den.getText() << ") X " << mul.getText() << " = " cLog(lsWARNING) << "(" << num.getText() << "/" << den.getText() << ") X " << mul.getText() << " = "
<< res.getText() << " not " << cmp.getText(); << res.getText() << " not " << cmp.getText();
BOOST_FAIL("Round fail");
return false;
} }
static void mulTest(int a, int b) static void mulTest(int a, int b)

View File

@@ -387,6 +387,9 @@ public:
static bool issuerFromString(uint160& uDstIssuer, const std::string& sIssuer); static bool issuerFromString(uint160& uDstIssuer, const std::string& sIssuer);
Json::Value getJson(int) const; Json::Value getJson(int) const;
STAmount getRound() const;
void roundSelf();
}; };
extern STAmount saZero; extern STAmount saZero;