41 lines
829 B
Go
41 lines
829 B
Go
|
package utility
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// FormatNumberShort compresses a number into as short a string as possible (e.g. "1.2K" when it gets into the thousands).
|
||
|
func FormatNumberShort(value int64) string {
|
||
|
// Under 1,000?
|
||
|
if value < 1000 {
|
||
|
return fmt.Sprintf("%d", value)
|
||
|
}
|
||
|
|
||
|
// Start to bucket it.
|
||
|
var (
|
||
|
thousands = float64(value) / 1000
|
||
|
millions = float64(thousands) / 1000
|
||
|
billions = float64(millions) / 1000
|
||
|
)
|
||
|
|
||
|
formatFloat := func(v float64) string {
|
||
|
s := strconv.FormatFloat(v, 'f', 1, 64)
|
||
|
if strings.HasSuffix(s, ".0") {
|
||
|
return strings.Split(s, ".")[0]
|
||
|
}
|
||
|
return s
|
||
|
}
|
||
|
|
||
|
if thousands < 1000 {
|
||
|
return fmt.Sprintf("%sK", formatFloat(thousands))
|
||
|
}
|
||
|
|
||
|
if millions < 1000 {
|
||
|
return fmt.Sprintf("%sM", formatFloat(millions))
|
||
|
}
|
||
|
|
||
|
return fmt.Sprintf("%sB", formatFloat(billions))
|
||
|
}
|