Skip to content

Commit

Permalink
add NewFromFloat #108 (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
npinochet authored Aug 3, 2022
1 parent e9a67ed commit e9d346f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ Initialize Money by using smallest unit value (e.g 100 represents 1 pound). Use
```go
pound := money.New(100, money.GBP)
```
Or initialize Money using the direct amount.
```go
quarterEuro := money.NewFromFloat(0.25, money.EUR)
```
Comparison
-
**Go-money** provides base compare operations like:
Expand Down
8 changes: 8 additions & 0 deletions money.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"math"
)

// Injection points for backward compatibility.
Expand Down Expand Up @@ -85,6 +86,13 @@ func New(amount int64, code string) *Money {
}
}

// NewFromFloat creates and returns new instance of Money from a float64.
// Always rounding trailing decimals down.
func NewFromFloat(amount float64, currency string) *Money {
currencyDecimals := math.Pow10(GetCurrency(currency).Fraction)
return New(int64(amount*currencyDecimals), currency)
}

// Currency returns the currency used by Money.
func (m *Money) Currency() *Currency {
return m.currency
Expand Down
18 changes: 18 additions & 0 deletions money_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,24 @@ func TestMoney_Amount(t *testing.T) {
}
}

func TestNewFromFloat(t *testing.T) {
m := NewFromFloat(12.34, EUR)

if m.amount != 1234 {
t.Errorf("Expected %d got %d", 1234, m.amount)
}

if m.currency.Code != EUR {
t.Errorf("Expected currency %s got %s", EUR, m.currency.Code)
}

m = NewFromFloat(-0.125, EUR)

if m.amount != -12 {
t.Errorf("Expected %d got %d", -12, m.amount)
}
}

func TestDefaultMarshal(t *testing.T) {
given := New(12345, IQD)
expected := `{"amount":12345,"currency":"IQD"}`
Expand Down

0 comments on commit e9d346f

Please sign in to comment.