diff options
Diffstat (limited to 'nmg_CM/nmg_CM.go')
-rw-r--r-- | nmg_CM/nmg_CM.go | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/nmg_CM/nmg_CM.go b/nmg_CM/nmg_CM.go index fc1c6152..12d98168 100644 --- a/nmg_CM/nmg_CM.go +++ b/nmg_CM/nmg_CM.go @@ -112,3 +112,42 @@ func (nmg *nmg_CM) FmtNumber(num float64, v uint64) []byte { return b } + +// FmtPercent returns 'num' with digits/precision of 'v' for 'nmg_CM' 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 (nmg *nmg_CM) FmtPercent(num float64, v uint64) []byte { + + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + l := len(s) + len(nmg.decimal) + + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, nmg.decimal[0]) + continue + } + + b = append(b, s[i]) + } + + if num < 0 { + for j := len(nmg.minus) - 1; j >= 0; j-- { + b = append(b, nmg.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] + } + + for j := len(nmg.percent) - 1; j >= 0; j-- { + b = append(b, nmg.percent[j]) + } + + return b +} |