From 8f548859d36cf2a8371698e97f1707119085074b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Pinochet?= Date: Mon, 1 Aug 2022 22:05:24 -0400 Subject: [PATCH] add NewFromFloat #108 --- README.md | 4 ++++ money.go | 8 ++++++++ money_test.go | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/README.md b/README.md index 2461b5e..d97747d 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/money.go b/money.go index cb3d76f..e735771 100644 --- a/money.go +++ b/money.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "math" ) // Injection points for backward compatibility. @@ -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 diff --git a/money_test.go b/money_test.go index 4be283b..196f5b5 100644 --- a/money_test.go +++ b/money_test.go @@ -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"}`