implement amount.go:Amount:AbsoluteValue

main
bel 2023-10-15 11:36:27 -06:00
parent 55422bb8af
commit 2e135f2e8f
2 changed files with 37 additions and 0 deletions

View File

@ -44,6 +44,13 @@ var localizedLanguagePrinter = func() *message.Printer {
return message.NewPrinter(result) return message.NewPrinter(result)
}() }()
func (amount Amount) AbsoluteValue() Amount {
if amount < 0 {
return -1.0 * amount
}
return amount
}
// Rounded rounds a float to the number of places specified. // Rounded rounds a float to the number of places specified.
func (amount Amount) Rounded(places int) Amount { func (amount Amount) Rounded(places int) Amount {
p := math.Pow10(places) p := math.Pow10(places)

View File

@ -87,3 +87,33 @@ func TestFormatUSD(t *testing.T) {
}) })
} }
} }
func TestAmountAbsoluteValue(t *testing.T) {
cases := map[string]struct {
input Amount
want Amount
}{
"zero": {
input: Amount(0.0),
want: Amount(0.0),
},
"positive unchanged": {
input: Amount(1.0),
want: Amount(1.0),
},
"negative unchanged": {
input: Amount(-0.000001),
want: Amount(0.000001),
},
}
for name, td := range cases {
tt := td // go bug through 1.21+ requires allocating a new variable or setting a go env for experimental features as of go 1.20 (1.21?)
t.Run(name, func(t *testing.T) {
got := tt.input.AbsoluteValue()
if got != tt.want {
t.Errorf("got \n\t%v, want\n\t%v", got, tt.want)
}
})
}
}