2023-12-22 01:12:34 +00:00
|
|
|
package utility
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2024-09-28 00:37:45 +00:00
|
|
|
// FormatFloatToPrecision will trim a floating point number to at most a number of decimals of precision.
|
|
|
|
//
|
|
|
|
// If the precision is ".0" the decimal place will be stripped entirely.
|
|
|
|
func FormatFloatToPrecision(v float64, prec int) string {
|
|
|
|
s := strconv.FormatFloat(v, 'f', prec, 64)
|
|
|
|
if strings.HasSuffix(s, ".0") {
|
|
|
|
return strings.Split(s, ".")[0]
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2023-12-22 01:12:34 +00:00
|
|
|
// 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
|
|
|
|
)
|
|
|
|
|
|
|
|
if thousands < 1000 {
|
2024-09-28 00:37:45 +00:00
|
|
|
return fmt.Sprintf("%sK", FormatFloatToPrecision(thousands, 1))
|
2023-12-22 01:12:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if millions < 1000 {
|
2024-09-28 00:37:45 +00:00
|
|
|
return fmt.Sprintf("%sM", FormatFloatToPrecision(millions, 1))
|
2023-12-22 01:12:34 +00:00
|
|
|
}
|
|
|
|
|
2024-09-28 00:37:45 +00:00
|
|
|
return fmt.Sprintf("%sB", FormatFloatToPrecision(billions, 1))
|
2023-12-22 01:12:34 +00:00
|
|
|
}
|