Add conversions between Number, XRPAmount and int64_t

* Conversions to Number are implicit
* Conversions away from Number are explicit and potentially lossy
* If lossy, round to nearest, and to even on tie
This commit is contained in:
Howard Hinnant
2022-04-15 16:20:52 -04:00
committed by Elliot Lee
parent 0ee63b7c7b
commit 476ee8a479
3 changed files with 117 additions and 0 deletions

View File

@@ -374,6 +374,45 @@ Number::operator/=(Number const& y)
return *this;
}
Number::operator rep() const
{
std::int64_t drops = mantissa_;
int offset = exponent_;
guard g;
if (drops != 0)
{
if (drops < 0)
{
g.set_negative();
drops = -drops;
}
for (; offset < 0; ++offset)
{
g.push(drops % 10);
drops /= 10;
}
for (; offset > 0; --offset)
{
if (drops > std::numeric_limits<decltype(drops)>::max() / 10)
throw std::runtime_error("Number::operator rep() overflow");
drops *= 10;
}
auto r = g.round();
if (r == 1 || (r == 0 && (drops & 1) == 1))
{
++drops;
}
if (g.is_negative())
drops = -drops;
}
return drops;
}
Number::operator XRPAmount() const
{
return XRPAmount{static_cast<rep>(*this)};
}
std::string
to_string(Number const& amount)
{