Skip to content

Commit

Permalink
Avoid string in amount_t::in_place_truncate
Browse files Browse the repository at this point in the history
Do not serialize to string just to get rounded value.
`in_place_roundto` should be reliable enough now.
  • Loading branch information
maxnikulin authored and jwiegley committed Aug 15, 2024
1 parent 61beb97 commit 6d61583
Showing 1 changed file with 1 addition and 26 deletions.
27 changes: 1 addition & 26 deletions src/amount.cc
Original file line number Diff line number Diff line change
Expand Up @@ -622,40 +622,15 @@ void amount_t::in_place_round()

void amount_t::in_place_truncate()
{
#if 1
if (! quantity)
throw_(amount_error, _("Cannot truncate an uninitialized amount"));

_dup();

DEBUG("amount.truncate",
"Truncating " << *this << " to precision " << display_precision());

std::ostringstream out;
stream_out_mpq(out, MP(quantity), display_precision());

scoped_array<char> buf(new char [out.str().length() + 1]);
std::strcpy(buf.get(), out.str().c_str());

char * q = buf.get();
for (char * p = q; *p != '\0'; p++, q++) {
if (*p == '.') p++;
if (p != q) *q = *p;
}
*q = '\0';

mpq_set_str(MP(quantity), buf.get(), 10);

mpz_ui_pow_ui(temp, 10, display_precision());
mpq_set_z(tempq, temp);
mpq_div(MP(quantity), MP(quantity), tempq);
in_place_roundto(display_precision());

DEBUG("amount.truncate", "Truncated = " << *this);
#else
// This naive implementation is straightforward, but extremely inefficient
// as it requires parsing the commodity too, which might be fully annotated.
*this = amount_t(to_string());
#endif
}

void amount_t::in_place_floor()
Expand Down

0 comments on commit 6d61583

Please sign in to comment.