From fb2acb93602d54a9be9ff735bcabbe17a66cb876 Mon Sep 17 00:00:00 2001 From: joeybloggs Date: Fri, 12 Aug 2016 22:28:58 -0400 Subject: add FmtPercent logic. --- eo/eo.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'eo/eo.go') diff --git a/eo/eo.go b/eo/eo.go index e610d1a9..2baeb15e 100644 --- a/eo/eo.go +++ b/eo/eo.go @@ -119,3 +119,40 @@ func (eo *eo) FmtNumber(num float64, v uint64) []byte { return b } + +// FmtPercent returns 'num' with digits/precision of 'v' for 'eo' and handles both Whole and Real numbers based on 'v' +// returned as a []byte just in case the caller wishes to add more and can help +// avoid allocations; otherwise just cast as string. +// NOTE: 'num' passed into FmtPercent is assumed to be in percent already +func (eo *eo) FmtPercent(num float64, v uint64) []byte { + + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + l := len(s) + len(eo.decimal) + + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, eo.decimal[0]) + continue + } + + b = append(b, s[i]) + } + + if num < 0 { + for j := len(eo.minus) - 1; j >= 0; j-- { + b = append(b, eo.minus[j]) + } + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + b = append(b, eo.Percent[0]) + + return b +} -- cgit v1.2.3