首页  >  文章  >  后端开发  >  如何使用 golang.org/x/text/currency 修复 Go 中的货币格式问题

如何使用 golang.org/x/text/currency 修复 Go 中的货币格式问题

Patricia Arquette
Patricia Arquette原创
2024-10-24 02:18:29664浏览

How to Fix Currency Formatting Issues in Go Using golang.org/x/text/currency

使用 golang.org/x/text/currency 进行货币格式化

在 Go 中将值格式化为货币时,golang.org/x /text/currency 包提供了一个方便的解决方案。但是,如果输出显示没有逗号或千位分隔符,本文将探讨潜在的原因和解决方案。

格式不正确:点与逗号

在提供的代码中,问题是由于直接使用currency.Symbol 而不是使用message.NewPrinter 提供的更全面的格式而产生的。正确的方法是使用 message.NewPrinter 来处理适当的特定于语言的格式:

<code class="go">func (produto *Produto) FormataPreco(valor int64) string {
    unit, _ := currency.ParseISO("BRL")
    p := message.NewPrinter(language.BrazilianPortuguese)
    return p.Sprint(unit.Amount(float64(valor) / 100))
}</code>

系统区域设置资源

要使用系统区域设置资源格式化货币,该解决方案需要从语言代码推断格式。这可以使用 display.Tags 来实现:

<code class="go">n := display.Tags(language.English)
for _, lcode := range []string{&quot;en_US&quot;, &quot;pt_BR&quot;, &quot;de&quot;, &quot;ja&quot;, &quot;hi&quot;} {
    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(&quot;%24v (%v): %v%v\n&quot;, n.Name(lang), cur, currency.Symbol(cur), dec)
}</code>

或者,可以解析 ISO 货币代码,但必须单独指定输出语言:

<code class="go">for _, iso := range []string{&quot;USD&quot;, &quot;BRL&quot;, &quot;EUR&quot;, &quot;JPY&quot;, &quot;INR&quot;} {
    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(&quot;%v: %v%v\n&quot;, cur, currency.Symbol(cur), dec)
}</code>

舍入要求

某些货币需要按增量舍入(例如 0.05 或 0.50)。为了适应这种情况,需要进行额外的处理来向 Decimal 格式化程序提供正确的 IncrementString:

<code class="go">scale, incCents := currency.Cash.Rounding(cur) // fractional digits
incFloat := math.Pow10(-scale) * float64(incCents)
incFmt := strconv.FormatFloat(incFloat, 'f', scale, 64)
dec := number.Decimal(100000.26,
    number.Scale(scale), number.IncrementString(incFmt))
p.Printf(&quot;%24v %v, %4s-rounding: %3v%v\n&quot;,
    n.Name(lang), cur, incFmt, currency.Symbol(cur), dec)</code>

通过利用这些方法,可以使用 golang.org/x/text/ 在 Go 中格式化货币值货币,同时确保基于系统区域设置资源或 ISO 货币代码的正确本地化和格式设置。

以上是如何使用 golang.org/x/text/currency 修复 Go 中的货币格式问题的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn