commaf.go

 1//go:build go1.6
 2// +build go1.6
 3
 4package humanize
 5
 6import (
 7	"bytes"
 8	"math/big"
 9	"strings"
10)
11
12// BigCommaf produces a string form of the given big.Float in base 10
13// with commas after every three orders of magnitude.
14func BigCommaf(v *big.Float) string {
15	buf := &bytes.Buffer{}
16	if v.Sign() < 0 {
17		buf.Write([]byte{'-'})
18		v.Abs(v)
19	}
20
21	comma := []byte{','}
22
23	parts := strings.Split(v.Text('f', -1), ".")
24	pos := 0
25	if len(parts[0])%3 != 0 {
26		pos += len(parts[0]) % 3
27		buf.WriteString(parts[0][:pos])
28		buf.Write(comma)
29	}
30	for ; pos < len(parts[0]); pos += 3 {
31		buf.WriteString(parts[0][pos : pos+3])
32		buf.Write(comma)
33	}
34	buf.Truncate(buf.Len() - 1)
35
36	if len(parts) > 1 {
37		buf.Write([]byte{'.'})
38		buf.WriteString(parts[1])
39	}
40	return buf.String()
41}