Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created May 12, 2015 01:59
Show Gist options
  • Save montanaflynn/cafe22b88dfc402ace5d to your computer and use it in GitHub Desktop.
Save montanaflynn/cafe22b88dfc402ace5d to your computer and use it in GitHub Desktop.
Short Number Count
package main
import (
"fmt"
"math"
"strconv"
)
func Round(input float64, places int) (rounded float64) {
if math.IsNaN(input) {
return input
}
sign := 1.0
if input < 0 {
sign = -1
input *= -1
}
precision := math.Pow(10, float64(places))
digit := input * precision
_, decimal := math.Modf(digit)
if decimal >= 0.5 {
rounded = math.Ceil(digit)
} else {
rounded = math.Floor(digit)
}
return rounded / precision * sign
}
func ShortCount(n float64) string {
var s string
prefix := []byte{'T', 'B', 'M', 'k'}
powers := []float64{1e+12, 1e+09, 1e+06, 1000}
for i := range prefix {
limit := powers[i]
if n > limit {
n = Round(n/limit, 0)
rounded := strconv.FormatFloat(n, 'f', -1, 64)
prefixed := string(prefix[i])
return fmt.Sprintf("%s%s", rounded, prefixed)
}
if i == len(prefix)-1 {
n = Round(n, 0)
return strconv.FormatFloat(n, 'f', -1, 64)
}
}
return s
}
func main() {
fmt.Println(ShortCount(30534533333443.023423))
fmt.Println(ShortCount(3054533333443.023423))
fmt.Println(ShortCount(305353333443.023423))
fmt.Println(ShortCount(30534333443.023423))
fmt.Println(ShortCount(3053534443.023423))
fmt.Println(ShortCount(305334443.023423))
fmt.Println(ShortCount(30533443.023423))
fmt.Println(ShortCount(3033443.023423))
fmt.Println(ShortCount(344443.023423))
fmt.Println(ShortCount(34443.023423))
fmt.Println(ShortCount(3043.023423))
fmt.Println(ShortCount(30.023423))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment