Skip to content

Instantly share code, notes, and snippets.

@rmrfslashbin
Last active September 22, 2021 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmrfslashbin/eb5720f9d8d46ab831577a3d92c31293 to your computer and use it in GitHub Desktop.
Save rmrfslashbin/eb5720f9d8d46ab831577a3d92c31293 to your computer and use it in GitHub Desktop.
Golang function to return a "simple number"
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(NumberFormat(123))
fmt.Println(NumberFormat(12345))
fmt.Println(NumberFormat(12345678))
fmt.Println(NumberFormat(1234567890123))
fmt.Println(NumberFormat(1234567890123456))
fmt.Println(NumberFormat(1234567890123456789))
}
func NumberFormat(num float64) string {
// Inspired by https://stackoverflow.com/a/66105942
units := [5]string{"k", "M", "B", "T", "Q"}
unit := len(fmt.Sprintf("%.0f", math.Floor(num/1.0e+1)))
x := math.Abs(num) / math.Pow(10, float64(unit-(unit%3)))
i := int(math.Floor(float64(unit)/3.0) - 1.0)
if i < 0 || i > len(units)-1 {
return fmt.Sprintf("%.0f", num)
}
return fmt.Sprintf("%.2f%s", x, units[i])
}
]$ go run .
123
12.35k
12.35M
1.23T
1.23Q
1234567890123456768
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment