Skip to content

Commit

Permalink
Fix a.BigInt() for negative amounts (the result was always positive).
Browse files Browse the repository at this point in the history
Fixes #27.
  • Loading branch information
bojanz committed Nov 19, 2023
1 parent 6f1903f commit b1ce3af
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
11 changes: 9 additions & 2 deletions amount.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,22 @@ func (a Amount) String() string {

// BigInt returns a in minor units, as a big.Int.
func (a Amount) BigInt() *big.Int {
r := a.Round()
return r.number.Coeff.MathBigInt()
a = a.Round()
n := a.number.Coeff.MathBigInt()
if a.IsNegative() {
// The coefficient is always positive, apd stores the sign separately.
n = n.Neg(n)
}

return n
}

// Int64 returns a in minor units, as an int64.
// If a cannot be represented in an int64, an error is returned.
func (a Amount) Int64() (int64, error) {
n := a.Round().number
n.Exponent = 0

return n.Int64()
}

Expand Down
4 changes: 4 additions & 0 deletions amount_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ func TestNewAmountFromBigInt(t *testing.T) {
wantNumber string
}{
{big.NewInt(2099), "USD", "20.99"},
{big.NewInt(-2099), "USD", "-20.99"},
{big.NewInt(5000), "USD", "50.00"},
{big.NewInt(50), "JPY", "50"},
{hugeInt, "USD", "9223372036854775987.99"},
Expand Down Expand Up @@ -163,6 +164,9 @@ func TestAmount_BigInt(t *testing.T) {
// Number with no decimals.
{"50", "USD", big.NewInt(5000)},
{"50", "JPY", big.NewInt(50)},
// Negative number.
{"-12.3564", "USD", big.NewInt(-1236)},
{"-50", "JPY", big.NewInt(-50)},
}

for _, tt := range tests {
Expand Down

0 comments on commit b1ce3af

Please sign in to comment.