diff options
author | joeybloggs <Dean.Karn@gmail.com> | 2016-08-12 19:15:42 +0300 |
---|---|---|
committer | joeybloggs <Dean.Karn@gmail.com> | 2016-08-12 19:15:42 +0300 |
commit | 7639a439740dfc3cdda4ae188bf3baf7cc2ff7a3 (patch) | |
tree | 7c43c1081bb3e25696701bd8e13ab0efee92cec4 /ar | |
parent | df0d272ef2250baaad947ff65501398623365e61 (diff) |
Add FmtNumber function + logic.
Diffstat (limited to 'ar')
-rw-r--r-- | ar/ar.go | 54 |
1 files changed, 54 insertions, 0 deletions
@@ -2,6 +2,7 @@ package ar import ( "math" + "strconv" "github.com/go-playground/locales" ) @@ -129,3 +130,56 @@ func (ar *ar) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) return locales.PluralRuleOther } + +// FmtNumber returns 'num' with digits/precision of 'v' for 'ar' 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. +func (ar *ar) FmtNumber(num float64, v uint64) []byte { + + s := strconv.FormatFloat(num, 'f', int(v), 64) + + l := len(s) + len(ar.decimal) + len(ar.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] == '.' { + + for j := len(ar.decimal) - 1; j >= 0; j-- { + b = append(b, ar.decimal[j]) + } + + inWhole = true + + continue + } + + if inWhole { + + if count == 3 { + + for j := len(ar.group) - 1; j >= 0; j-- { + b = append(b, ar.group[j]) + } + + count = 1 + } else { + count++ + } + } + + b = append(b, s[i]) + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + return b + +} |