commaf.go 745 B

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