diff --git a/amount.go b/amount.go index 1d1e2d7..a15b311 100644 --- a/amount.go +++ b/amount.go @@ -122,8 +122,14 @@ 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. @@ -131,6 +137,7 @@ func (a Amount) BigInt() *big.Int { func (a Amount) Int64() (int64, error) { n := a.Round().number n.Exponent = 0 + return n.Int64() } diff --git a/amount_test.go b/amount_test.go index 148dc02..dce7e96 100644 --- a/amount_test.go +++ b/amount_test.go @@ -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"}, @@ -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 {