Last active
September 22, 2021 21:09
-
-
Save rmrfslashbin/eb5720f9d8d46ab831577a3d92c31293 to your computer and use it in GitHub Desktop.
Golang function to return a "simple number"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
]$ 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