Numbers with thousands separators using Golang
How to format numbers like this in Go
You have a number, say 12951267, and you want separators in so it shows more like 12,951,267 (or 12.951.267 if you prefer).
There is nothing built into Go that formats numbers like that, with thousands separators (or millions, billions and so forth). Here's a simple function to do it.
An overview of how it works
The most obvious first step is to convert from 12951267 to "12951267", i.e. make it a string so you can insert the separators.
If you simply run from the start to the end of the string inserting the separator character, then your life is complicated by your position being from the left but the grouping from the right so you'll have groupings of three left to right but may end up with less than three in the last group instead of the first.
The easy answer is to reverse the string, making sure that as you create the result a separator is added after every third digit. So, "12951267" becomes "762,159,21" - you can see how simple it is to know where the separator goes.
Finally, simply reverse the string again and return it ("12,951,267").
The code to do it
I've done it with a hard-coded comma separator as my internal project only ever uses that format. Switching or specifying the character would be trivial.
// prettyNumber ... Returns a string representation with thousand separator.
func prettyNumber(i int) string {
s := strconv.Itoa(i)
r1 := ""
idx := 0
// Reverse and interleave the separator.
for i = len(s) - 1; i >= 0; i-- {
idx++
if idx == 4 {
idx = 1
r1 = r1 + ","
}
r1 = r1 + string(s[i])
}
// Reverse back and return.
r2 := ""
for i = len(r1) - 1; i >= 0; i-- {
r2 = r2 + string(r1[i])
}
return r2
}