From aaa28727a7fc0cc7add5d60b31abfe62b983bedd Mon Sep 17 00:00:00 2001 From: joeybloggs Date: Mon, 15 Aug 2016 21:59:49 -0400 Subject: add accounting currency formatting logic + function --- prg/prg.go | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) (limited to 'prg') diff --git a/prg/prg.go b/prg/prg.go index d74b6838..2c6cf79f 100644 --- a/prg/prg.go +++ b/prg/prg.go @@ -64,8 +64,8 @@ func (prg *prg) CardinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) f := locales.F(n, v) - nMod10 := math.Mod(n, 10) nMod100 := math.Mod(n, 100) + nMod10 := math.Mod(n, 10) fMod100 := f % 100 fMod10 := f % 10 @@ -232,3 +232,78 @@ func (prg *prg) FmtCurrency(num float64, v uint64, currency currency.Type) []byt return b } + +// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'prg' +// in accounting notation. returned as a []byte just in case the caller wishes to add more and can help +// avoid allocations; otherwise just cast as string. +func (prg *prg) FmtAccounting(num float64, v uint64, currency currency.Type) []byte { + + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + symbol := prg.currencies[currency] + l := len(s) + len(prg.decimal) + len(prg.group)*len(s[:len(s)-int(v)-1])/3 + count := 0 + inWhole := v == 0 + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, prg.decimal[0]) + inWhole = true + + continue + } + + if inWhole { + if count == 3 { + for j := len(prg.group) - 1; j >= 0; j-- { + b = append(b, prg.group[j]) + } + + count = 1 + } else { + count++ + } + } + + b = append(b, s[i]) + } + + if num < 0 { + + b = append(b, prg.minus[0]) + + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + if int(v) < 2 { + + if v == 0 { + b = append(b, prg.decimal...) + } + + for i := 0; i < 2-int(v); i++ { + b = append(b, '0') + } + } + + if num < 0 { + + b = append(b, prg.currencyNegativeSuffix...) + + b = append(b, symbol...) + + } else { + + b = append(b, prg.currencyPositiveSuffix...) + + b = append(b, symbol...) + + } + + return b +} -- cgit v1.2.3