format.go 766 B

12345678910111213141516171819202122232425262728293031323334
  1. package format
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. const (
  7. Thousand = 1000
  8. Million = Thousand * 1000
  9. Billion = Million * 1000
  10. )
  11. func HumanNumber(b uint64) string {
  12. switch {
  13. case b >= Billion:
  14. number := float64(b) / Billion
  15. if number == math.Floor(number) {
  16. return fmt.Sprintf("%.0fB", number) // no decimals if whole number
  17. }
  18. return fmt.Sprintf("%.1fB", number) // one decimal if not a whole number
  19. case b >= Million:
  20. number := float64(b) / Million
  21. if number == math.Floor(number) {
  22. return fmt.Sprintf("%.0fM", number) // no decimals if whole number
  23. }
  24. return fmt.Sprintf("%.2fM", number) // two decimals if not a whole number
  25. case b >= Thousand:
  26. return fmt.Sprintf("%.0fK", float64(b)/Thousand)
  27. default:
  28. return fmt.Sprintf("%d", b)
  29. }
  30. }