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
Add a comment  | 

1 Answer 1

Reset to default 0

You 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