Skip to content

Commit b1ce3af

Browse files
committed
Fix a.BigInt() for negative amounts (the result was always positive).
Fixes #27.
1 parent 6f1903f commit b1ce3af

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

amount.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -122,15 +122,22 @@ func (a Amount) String() string {
122122

123123
// BigInt returns a in minor units, as a big.Int.
124124
func (a Amount) BigInt() *big.Int {
125-
r := a.Round()
126-
return r.number.Coeff.MathBigInt()
125+
a = a.Round()
126+
n := a.number.Coeff.MathBigInt()
127+
if a.IsNegative() {
128+
// The coefficient is always positive, apd stores the sign separately.
129+
n = n.Neg(n)
130+
}
131+
132+
return n
127133
}
128134

129135
// Int64 returns a in minor units, as an int64.
130136
// If a cannot be represented in an int64, an error is returned.
131137
func (a Amount) Int64() (int64, error) {
132138
n := a.Round().number
133139
n.Exponent = 0
140+
134141
return n.Int64()
135142
}
136143

amount_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ func TestNewAmountFromBigInt(t *testing.T) {
9090
wantNumber string
9191
}{
9292
{big.NewInt(2099), "USD", "20.99"},
93+
{big.NewInt(-2099), "USD", "-20.99"},
9394
{big.NewInt(5000), "USD", "50.00"},
9495
{big.NewInt(50), "JPY", "50"},
9596
{hugeInt, "USD", "9223372036854775987.99"},
@@ -163,6 +164,9 @@ func TestAmount_BigInt(t *testing.T) {
163164
// Number with no decimals.
164165
{"50", "USD", big.NewInt(5000)},
165166
{"50", "JPY", big.NewInt(50)},
167+
// Negative number.
168+
{"-12.3564", "USD", big.NewInt(-1236)},
169+
{"-50", "JPY", big.NewInt(-50)},
166170
}
167171

168172
for _, tt := range tests {

0 commit comments

Comments
 (0)