Skip to content

Commit

Permalink
Add Val() method. (#10)
Browse files Browse the repository at this point in the history
* Add Val() method.

Usecases:
- Custom serialization / deserialization
- Persisting Amount as two columns in a database

* Rename Val() to Scaled().

Co-authored-by: Nikolay Dubina <nikolay.dubina.pub@gmail.com>
Signed-off-by: Michael Würtinger <michael@wuertinger.de>

* Add TestScaled.

* Rename package back to fpmoney_test.

* Turn test into examples.

Co-authored-by: Nikolay Dubina <nikolay.dubina.pub@gmail.com>
Signed-off-by: Michael Würtinger <michael@wuertinger.de>

---------

Signed-off-by: Michael Würtinger <michael@wuertinger.de>
Co-authored-by: Nikolay Dubina <nikolay.dubina.pub@gmail.com>
  • Loading branch information
mwuertinger and nikolaydubina authored Sep 3, 2024
1 parent 1073564 commit 4f5dd8e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions amount.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ func (a Amount) Float64() float64 { return float64(a.v) / float64(a.c.scale()) }

func (a Amount) Currency() Currency { return a.c }

func (a Amount) Scaled() int64 { return a.v }

func (a Amount) Add(b Amount) Amount {
checkCurrency(a.c, b.c)
return Amount{v: a.v + b.v, c: a.c}
Expand Down
29 changes: 29 additions & 0 deletions amount_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,35 @@ func ExampleFromFloat() {
// Output: 144.96 SGD
}

func ExampleAmount_Scaled_fractions() {
v := fpmoney.FromFloat(42.23, fpmoney.EUR)
fmt.Println(v.Scaled())
// Output: 4223
}

func ExampleAmount_Scaled_many_fractions() {
v := fpmoney.FromFloat(17.0, fpmoney.CLF)
fmt.Println(v.Scaled())
// Output: 170000
}

func ExampleAmount_Scaled_large() {
v := fpmoney.FromFloat(8764534896.42, fpmoney.USD)
fmt.Println(v.Scaled())
// Output: 876453489642
}
func ExampleAmount_Scaled_whole() {
v := fpmoney.FromFloat(23.0, fpmoney.EUR)
fmt.Println(v.Scaled())
// Output: 2300
}

func ExampleAmount_Scaled_from_scaled() {
v := fpmoney.FromIntScaled(17, fpmoney.EUR)
fmt.Println(v.Scaled())
// Output: 17
}

func FuzzArithmetics(f *testing.F) {
currencies := [...]fpmoney.Currency{
fpmoney.KRW,
Expand Down

0 comments on commit 4f5dd8e

Please sign in to comment.