Edit: I was wrong about rounding/truncating.
The problem with %.2f
formatting is that it does not round but truncates.
I've developed a decimal class based on int64 for handling money that is handling floats, string parsing, JSON, etc.
It stores amount as 64 bit integer number of cents. Can be easily created from float or converted back to float.
Handy for storing in DB as well.
https://github.com/strongo/decimal
package example
import "github.com/strongo/decimal"
func Example() {
var amount decimal.Decimal64p2; print(amount) // 0
amount = decimal.NewDecimal64p2(0, 43); print(amount) // 0.43
amount = decimal.NewDecimal64p2(1, 43); print(amount) // 1.43
amount = decimal.NewDecimal64p2FromFloat64(23.100001); print(amount) // 23.10
amount, _ = decimal.ParseDecimal64p2("2.34"); print(amount) // 2.34
amount, _ = decimal.ParseDecimal64p2("-3.42"); print(amount) // -3.42
}
Works well for my debts tracker app https://debtstracker.io/