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