package utility

import (
	"fmt"
	"strconv"
	"strings"
)

// 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
}

// 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 {
		return fmt.Sprintf("%sK", FormatFloatToPrecision(thousands, 1))
	}

	if millions < 1000 {
		return fmt.Sprintf("%sM", FormatFloatToPrecision(millions, 1))
	}

	return fmt.Sprintf("%sB", FormatFloatToPrecision(billions, 1))
}