The standard lib (and the fmt
package) does not support localized text and number formatting.
If you only need to localize the decimal point, you may use the easy way to simply replace the dot (.
) with the comma character (,
) like this:
percentageValue := 52.12
s := fmt.Sprintf("%.2f%%", percentageValue)
s = strings.Replace(s, ".", ",", -1)
fmt.Println(s)
(Also note that you may output a percent sign %
by using 2 percent signs %%
in the format string.)
Which outputs (try it on the Go Playground):
52,12%
Or with a mapping function:
func dot2comma(r rune) rune {
if r == '.' {
return ','
}
return r
}
func main() {
percentageValue := 52.12
s := fmt.Sprintf("%.2f%%", percentageValue)
s = strings.Map(dot2comma, s)
fmt.Println(s)
}
Output is the same. Try this one on the Go Playground.
Yet another solution could be to format the integer and fraction part separately, and glue them together with a comma ,
sign:
percentageValue := 52.12
i, f := math.Modf(percentageValue)
s := fmt.Sprint(i) + "," + fmt.Sprintf("%.2f%%", f)[2:]
fmt.Println(s)
Try this one on the Go Playground.
Note that this latter solution needs "adjusting" if the percent value is negative:
percentageValue := -52.12
i, f := math.Modf(percentageValue)
if f < 0 {
f = -f
}
s := fmt.Sprint(i) + "," + fmt.Sprintf("%.2f%%", f)[2:]
fmt.Println(s)
This modified version will now print -52,12%
properly. Try it on the Go Playground.
If you need "full" localization support, then do check out and use golang.org/x/text/message
, which "implements formatted I/O for localized strings with functions analogous to the fmt's print functions. It is a drop-in replacement for fmt."