使用 golang 时。 org/x/text/currency 来格式化 Golang 中的货币值,可以通过利用 DisplayTags 和 FromTag 函数从系统语言环境中检索适当的格式。 DisplayTags 函数提供语言的本地化名称,FromTag 根据语言标签检索货币。
<code class="go">n := display.Tags(language.English) for _, lcode := range []string{"en_US", "pt_BR", "de", "ja", "hi"} { lang := language.MustParse(lcode) cur, _ := currency.FromTag(lang) scale, _ := currency.Cash.Rounding(cur) // fractional digits dec := number.Decimal(100000.00, number.Scale(scale)) p := message.NewPrinter(lang) p.Printf("%24v (%v): %v%v\n", n.Name(lang), cur, currency.Symbol(cur), dec) } // Output: // American English (USD): 0,000.00 // Brazilian Portuguese (BRL): R0.000,00 // German (EUR): €100.000,00 // Japanese (JPY): ¥100,000 // Hindi (INR): ₹1,00,000.00</code>
或者,您可以显式指定语言或 ISO货币代码以检索正确的货币格式。但是,您必须提供用于格式化数字的语言:
<code class="go">// Parse ISO currency code and specify language for _, iso := range []string{"USD", "BRL", "EUR", "JPY", "INR"} { cur := currency.MustParseISO(iso) scale, _ := currency.Cash.Rounding(cur) // fractional digits dec := number.Decimal(100000.00, number.Scale(scale)) p := message.NewPrinter(language.English) p.Printf("%v: %v%v\n", cur, currency.Symbol(cur), dec) } // Output: // USD: 0,000.00 // BRL: R0,000.00 // EUR: €100,000.00 // JPY: ¥100,000 // INR: ₹100,000.00</code>
以上是如何利用系统区域设置资源在 Go 中进行货币格式化?的详细内容。更多信息请关注PHP中文网其他相关文章!