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% .
You can do it like this: printf("%. 6f", myFloat); 6 represents the number of digits after the decimal separator.
The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.
The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.
To round a floating-point number in Go, you can use the math. Round() function from the built-in math package.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With