Skip to content

Commit

Permalink
Merge pull request #7 from radicalcompany/feature/amount_as_string
Browse files Browse the repository at this point in the history
Added method to get only amount as string
  • Loading branch information
thatside committed Apr 23, 2020
2 parents dab2792 + 3c04e0b commit b0c0ebe
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 14 deletions.
20 changes: 14 additions & 6 deletions convert/conversion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,25 @@ func TestConvertTo(t *testing.T) {
wantRes: money.MustForge(110, "USD"),
wantErr: false,
},
{
name: "gbp_to_usd",
args: args{
obj: money.MustForge(100, "GBP"),
rate: ForgeRate(money.MustGetCurrencyByISOCode("USD"), money.MustGetCurrencyByISOCode("EUR"), 2),
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotRes, err := ConvertTo(&tt.args.obj, tt.args.rate)
if (err != nil) != tt.wantErr {
t.Errorf("ConvertTo() error = %v, wantErr %v", err, tt.wantErr)
return
if tt.wantErr {
assert.NotNil(t, err)
}
assert.NotNil(t, gotRes)
if !assert.True(t, gotRes.IsEquals(tt.wantRes)) {
t.Errorf("ConvertTo() gotRes = %v, want %v", gotRes, tt.wantRes)
if gotRes != nil {
if !assert.True(t, gotRes.IsEquals(tt.wantRes)) {
t.Errorf("ConvertTo() result = %v, want %v", gotRes, tt.wantRes)
}
}
})
}
Expand Down
20 changes: 12 additions & 8 deletions money.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ func (m Money) Int64() int64 {
return int64(m.Amount)
}

func (m Money) Float() float64 {
if m.IsZero() {
return 0
}
d := m.DigitsAsCents()
return float64(m.Amount) / float64(d)
}

func (m Money) AmountAsString() string {
return fmt.Sprintf("%.2f", m.Float())
}

// Forge
// amount int64 A positive integer in cents
// currCode string Three-letter ISO currency code, in lowercase
Expand Down Expand Up @@ -96,14 +108,6 @@ func (m Money) IsZero() bool {
return m.Amount == 0
}

func (m Money) Float() float64 {
if m.IsZero() {
return 0
}
d := m.DigitsAsCents()
return float64(m.Amount) / float64(d)
}

func (m Money) DigitsAsCents() int {
return m.Currency.GetCents()
}
Expand Down
7 changes: 7 additions & 0 deletions money_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ func TestFloat(t *testing.T) {
assert.Equal(t, OneEurAndOneCent.Float(), 1.01)
}

func TestAmountAsString(t *testing.T) {
OneEurAndOneCent := money.FloatEUR(1.01)

assert.Equal(t, OneEurAndOneCent.Int64(), int64(101))
assert.Equal(t, OneEurAndOneCent.AmountAsString(), "1.01")
}

func TestMoney_IsEquals(t *testing.T) {
OneEurAndOneCent := money.FloatEUR(1.01)

Expand Down

0 comments on commit b0c0ebe

Please sign in to comment.