Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
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