Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): add String method to scw.Money #284

Merged
merged 3 commits into from
Jan 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions scw/custom_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import (
"fmt"
"io"
"net"
"strings"
"time"

"github.com/scaleway/scaleway-sdk-go/logger"
)

// ServiceInfo contains API metadata
Expand Down Expand Up @@ -82,6 +85,25 @@ func NewMoneyFromFloat(value float64, currency string) *Money {
}
}

// String returns the string representation of Money.
func (m *Money) String() string {
currencySignsByCodes := map[string]string{
"EUR": "€",
"USD": "$",
}

currencySign, currencySignFound := currencySignsByCodes[m.CurrencyCode]
if !currencySignFound {
logger.Debugf("%s currency code is not supported", m.CurrencyCode)
currencySign = m.CurrencyCode
}

cents := fmt.Sprintf("%09d", m.Nanos)
cents = cents[:2] + strings.TrimRight(cents[2:], "0")

return fmt.Sprintf("%s %d.%s", currencySign, m.Units, cents)
}

// ToFloat converts a Money object to a float.
func (m *Money) ToFloat() float64 {
return float64(m.Units) + float64(m.Nanos)/1000000000
Expand Down
56 changes: 56 additions & 0 deletions scw/custom_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,62 @@ import (
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
)

func TestMoney_String(t *testing.T) {
cases := []struct {
money Money
want string
}{
{
money: Money{
CurrencyCode: "EUR",
Units: 10,
},
want: "€ 10.00",
},
{
money: Money{
CurrencyCode: "USD",
Units: 10,
Nanos: 1,
},
want: "$ 10.000000001",
},
{
money: Money{
CurrencyCode: "EUR",
Nanos: 100000000,
},
want: "€ 0.10",
},
{
money: Money{
CurrencyCode: "EUR",
Nanos: 500000,
},
want: "€ 0.0005",
},
{
money: Money{
CurrencyCode: "EUR",
Nanos: 123456789,
},
want: "€ 0.123456789",
},
{
money: Money{
CurrencyCode: "?",
},
want: "? 0.00",
},
}

for _, c := range cases {
t.Run(c.want, func(t *testing.T) {
testhelpers.Equals(t, c.want, c.money.String())
})
}
}

func TestSize_String(t *testing.T) {
cases := []struct {
size Size
Expand Down