commaf.go

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