commaf.go 762 B

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