admin管理员组文章数量:1122846
I'm trying to convert a float64 currency '1000.99' to the string '£1,000.99'. The currency is not always £, and I'd like to decoration to be language/region specific (e.g. some places format it as '£1.000.99', others might do '£10,00.99'.
I have the ISO codes for the currency and the language, and I've found the package golang/x/currency, but the documentation doesn't really state how it actually works. So far I have the following:
func Format(val float64, currency, language string) (string, error) {
unit, err := currency.ParseISO(currency)
if err != nil {
return err
}
amount := unit.Amount(val)
// I know I need to call amount.Format(state, rune), but I have no idea how to create a state or a rune?
}
How do I construct a state and rune for a given ISO language?
I'm trying to convert a float64 currency '1000.99' to the string '£1,000.99'. The currency is not always £, and I'd like to decoration to be language/region specific (e.g. some places format it as '£1.000.99', others might do '£10,00.99'.
I have the ISO codes for the currency and the language, and I've found the package golang.org/x/currency, but the documentation doesn't really state how it actually works. So far I have the following:
func Format(val float64, currency, language string) (string, error) {
unit, err := currency.ParseISO(currency)
if err != nil {
return err
}
amount := unit.Amount(val)
// I know I need to call amount.Format(state, rune), but I have no idea how to create a state or a rune?
}
How do I construct a state and rune for a given ISO language?
Share Improve this question asked Nov 22, 2024 at 16:29 AndyAndy 3,5229 gold badges43 silver badges73 bronze badges 1- 5 Unrelated to your original question, but do not use floating point for currency. Floating point values are for scientific computations. They are not exact. – Burak Serdar Commented Nov 22, 2024 at 16:31
1 Answer
Reset to default 0You don't use amount.Format
directly, but via a message.Printer
(Go Playground):
package main
import (
"golang.org/x/text/currency"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
func main() {
amount := currency.GBP.Amount(1000.99)
LangPrint(language.English, amount)
LangPrint(language.German, amount)
}
func LangPrint(t language.Tag, amount currency.Amount) {
p := message.NewPrinter(t)
p.Printf("%v: %v\n", t, amount)
}
prints
en: GBP 1,000.99
de: GBP 1.000,99
本文标签: How do I format currency strings in goStack Overflow
版权声明:本文标题:How do I format currency strings in go? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736302351a1931503.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论