Reputation: 3410
I am printing floating point value(eg: 52.12
) like this:
fmt.Sprintf("%.2f%s", percentageValue, "%%")
Output is like 52.12%
. But I want to print it in other language than English where decimal point is comma ,
. How to do it in Go using fmt.Sprintf
. I want output like this 52,12% .
Upvotes: 11
Views: 10953
Reputation: 79674
The fmt
package does not support the functionality to replace the delimiter in a floating point number. You should instead use the golang.org/x/text/message package, which is designed for this purpose.
Upvotes: 13
Reputation: 3410
I have solved the problem by this:
func getFormattedValue(percentageValue float64) string{
value := fmt.Sprintf("%.2f%s", percentageValue, "%")
return strings.Replace(value, ".", ",", -1)
}
I am taking float value and converting to string then replacing .
with ,
Upvotes: 0
Reputation: 418077
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."
Upvotes: 7
Reputation: 122
I found a library to do that, it's called humanize.
With this you can do something like this fmt.Println(humanize.FormatFloat("00,00", 52.20))
See in the link below the instructions: https://github.com/dustin/go-humanize
Upvotes: 2