i18n

package
v0.0.0-...-d4f462a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 4, 2015 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package i18n supports string translations with variable substitution, CLDR pluralization, currency, formats, language, regions and timezones.

Decimals

A decimal number, or just decimal, refers to any number written in decimal notation, although it is more commonly used to refer to numbers that have a fractional part separated from the integer part with a decimal separator (e.g. 11.25) 11 is the integer part, dot the decimal separator and 25 the fractional part.

Number Format

A format like #,##0.00;(#,##0.00) consists of two parts. The first required part will be used for negative and positive numbers and if there is a second part after the semi-colon then this format will be solely used for formatting of negative numbers. More pattern details can be found: http://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns Formatting with a format like #,##,##0.00 is currently not implemented as too rarely used.

Number formatting

To instantiate your custom number formatter:

nf := i18n.NewNumber(
	i18n.NumberFormat("#,##0.00;(#,##0.00)" [, Symbols{Decimal: ',' ... } ] ),
)
nf.FmtNumber(w io.Writer, sign int, intgr, dec int64) (int, error)

Sign can be 1 for positive number and -1 for negative. intgr is the integer part and dec the decimal aka fractal part of your float. Roundings will be applied if dec does not fit within the decimals specified in the format.

There are also short hand methods for FmtInt(w io.Writer, i int) (int, error) and FmtFloat64(w io.Writer, f float64) (int, error).

For more information read the details in the documentation of the functions and types.

Currency formatting

To instantiate your custom currency formatter:

cf := i18n.NewCurrency(
	CurrencyISO("3-letter ISO 4217 code"),
	CurrencySign(s []byte),
	CurrencyFormat("#,##0.00 ¤" [, Symbols{Decimal: ',' ... } ] ),
	CurrencyFraction(digits, rounding, cashDigits, cashRounding int)
)
cf.FmtCurrency(w io.Writer, sign int, i, dec int64) (int, error)

CurrencyFraction: Digits are important when your currency has a different amount of decimal places as specified in the format. E.g. Japanese Yen has Digits 0 despite the format is #,##0.00 ¤.

@todo: Rounding refers to the Swedish rounding and are a todo in this i18n package. Use the money.Currency type for Swedish rounding. @todo: CashDigits and CashRounding are currently not implemented.

Currency Format

The currency symbol ¤ specifies where the currency sign will be placed.

Index

Constants

View Source
const (
	// LocaleDefault is the overall default locale when no website/store setting is available.
	LocaleDefault = "en_US"
	// CLDRVersionRequired required version to run this package
	CLDRVersionRequired = "27.0.1"
)
View Source
const DefaultCurrencyFormat = "¤\u00a0#,##0.00"

DefaultCurrencyFormat Symbol no-breaking-space 1,000.00

View Source
const DefaultCurrencyName = "XXX"

DefaultCurrencyName 3-letter ISO 4217 code

View Source
const DefaultNumberFormat = `#,##0.###`

DefaultNumberFormat 1,000.000

View Source
const LocaleSeparator = "_"

LocaleSeparator defines the underscore because in Magento land we also have the underscore as a separator. http://www.unicode.org/reports/tr35/#Language_and_Locale_IDs

Variables

View Source
var (
	ErrCannotDetectMinusSign = errors.New("Cannot detect minus sign")
	ErrPrecIsTooShort        = errors.New("Argument precision does not match with the amount of digits in frac. Prec is too short.")
)
View Source
var DefaultCurrencySign = []byte("$")

DefaultCurrencySign is the classical Dollar $

View Source
var LocaleAvailable utils.StringSlice

Available contains all available locales. One should not modify this slice.

View Source
var LocaleSupported utils.StringSlice

Supported contains all supported locales by this package. One should not modify this slice.

Functions

func AllCurrencies

func AllCurrencies(locale language.Tag)

func GetAllLanguages

func GetAllLanguages()

func GetLanguages

func GetLanguages(t language.Tag) []string

GetLanguages returns a list of languages as a key/value slice. Odd index/key = locale, even index/value = Humanized readable string. The humanized strings contains the language name in its language and language name in requested tag

func GetLocale

func GetLocale(b language.Base, r language.Region, s ...language.Script) string

GetLocale generates a locale from a base and a region and may use an optional script. lang lang_script lang_script_region lang_region (aliases to lang_script_region)

func GetLocaleTag

func GetLocaleTag(locale string) (language.Tag, error)

GetLocale creates a new language Tag from a locale

func NewCurrencyDict

func NewCurrencyDict(locale string, ti tagIndex, currencyNames, currencySymbols header) currencyDict

func NewHeader

func NewHeader(d string, i []uint16) header

func NewTagIndex

func NewTagIndex(ti [3]string) tagIndex

func SetCurrencyDict

func SetCurrencyDict(cds ...currencyDict)

Types

type CountrySlice

type CountrySlice []language.Region
var Countries CountrySlice

Countries contains all supported countries

type Currency

type Currency struct {
	*Number
	// ISO contains the 3-letter ISO 4217 currency code.
	// Maybe one day that will get extended in text/language package ...
	ISO language.Currency
	// contains filtered or unexported fields
}

Currency represents a locale specific formatter for a currency. You must use NewCurrency() to create a new type.

func NewCurrency

func NewCurrency(opts ...CurrencyOptFunc) *Currency

NewCurrency creates a new Currency pointer with default settings. To change the symbols depending on the locale: see documentation.

func (*Currency) COptions

func (c *Currency) COptions(opts ...CurrencyOptFunc) (previous CurrencyOptFunc)

COptions applies currency options and returns the last applied previous option function. For more details please read here http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html This function is thread safe.

func (*Currency) FmtFloat64

func (c *Currency) FmtFloat64(w io.Writer, f float64) (int, error)

FmtCurrencyFloat64 formats a float value, does internal maybe incorrect rounding. Returns the number bytes written or an error. Thread safe.

func (*Currency) FmtInt64

func (c *Currency) FmtInt64(w io.Writer, i int64) (int, error)

FmtInt64 formats an integer according to the currency format pattern. Thread safe

func (*Currency) FmtNumber

func (c *Currency) FmtNumber(w io.Writer, sign int, intgr int64, prec int, frac int64) (int, error)

FmtNumber formats a number according to the currency format. Internal rounding will be applied. Returns the number bytes written or an error. Thread safe. For more details please see the interface documentation.

func (*Currency) Sign

func (c *Currency) Sign() []byte

Sign returns the currency sign. Can be one character or a 3-letter ISO 4217 code.

type CurrencyDictSlice

type CurrencyDictSlice []currencyDict

type CurrencyFormatter

type CurrencyFormatter interface {
	// NumberFormatter functions for formatting. Please see interface description
	// about the contract.
	NumberFormatter
	// Sign returns the currency sign. Can be one character or a 3-letter ISO 4217 code.
	Sign() []byte
}

CurrencyFormatter knows locale specific properties about a currency/number

var DefaultCurrency CurrencyFormatter

DefaultCurrency represents the package wide default currency locale specific formatter.

type CurrencyFractions

type CurrencyFractions struct {
	// Digits the minimum and maximum number of decimal digits normally
	// formatted. The default is 2. For example, in the en_US locale with
	// the default value of 2 digits, the value 1 USD would format as
	// "$1.00", and the value 1.123 USD would format as → "$1.12".
	// Having a format like #,##0.00 ¤ would result in a French locale
	// 1 234,57 € and 1 235 ¥JP. Means for Euro we have 2 digits and
	// for the Yen 0 digits. Default value is 2.
	// ⚠ Warning: Digits will override the fraction part in the
	// format string, if Digits is > 0 ⚠.
	Digits int
	// Rounding increment, in units of 10-digits. The default is 0, which
	// means no rounding is to be done. Therefore, rounding=0 and rounding=1
	// have identical behavior. Thus with fraction digits of 2 and rounding
	// increment of 5, numeric values are rounded to the nearest 0.05 units
	// in formatting. With fraction digits of 0 and rounding increment of
	// 50, numeric values are rounded to the nearest 50.
	// ⚠ Warning: Rounding must be applied in the package money ⚠ @todo
	Rounding int
	// CashDigits the number of decimal digits to be used when formatting
	// quantities used in cash transactions (as opposed to a quantity that
	// would appear in a more formal setting, such as on a bank statement).
	// If absent, the value of "digits" should be used as a default.
	// Default value is 2. @todo
	CashDigits int
	// CashRounding increment, in units of 10-cashDigits. The default is 0,
	// which means no rounding is to be done; and as with rounding, this
	// has the same effect as cashRounding="1". This is the rounding increment
	// to be used when formatting quantities used in cash transactions (as
	// opposed to a quantity that would appear in a more formal setting,
	// such as on a bank statement). If absent, the value of "rounding"
	// should be used as a default. @todo
	CashRounding int
}

CurrencyFractions element contains any number of info elements. No negative values allowed ⚠.

type CurrencyOptFunc

type CurrencyOptFunc func(*Currency) CurrencyOptFunc

CurrencyOptFunc applies options to the Currency struct. To read more about the recursion pattern: http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html

func CurrencyFormat

func CurrencyFormat(f string, s ...Symbols) CurrencyOptFunc

CurrencyFormat applies a format (e.g.: #,##0.00 ¤) to a Number. If you do not have set the second argument Symbols (will be merge into) then the default Symbols will be used. Only one second argument is supported. If format is empty, fallback to the default format. A "¤" shows where the currency sign will go.

func CurrencyFraction

func CurrencyFraction(digits, rounding, cashDigits, cashRounding int) CurrencyOptFunc

CurrencyFraction sets the currency fractions. For details please see CurrencyFractions. Values below 0 will be reset to zero.

func CurrencyISO

func CurrencyISO(cur string) CurrencyOptFunc

CurrencyISO parses a 3-letter ISO 4217 code and sets it to the Currency struct. If parsing fails errors will be logged and falls back to DefaultCurrencyName. Calling this function sets also the CurrencySign() to the at the moment 3-letter ISO code. (Missing feature in text/language package) This function is called in NewCurrency().

func CurrencySign

func CurrencySign(s []byte) CurrencyOptFunc

CurrencySign sets the currency sign.

func CurrencySymbols

func CurrencySymbols(s Symbols) CurrencyOptFunc

CurrencySymbols sets the Symbols tables. The argument will be merged into the default Symbols table

type Number

type Number struct {
	// contains filtered or unexported fields
}

func NewNumber

func NewNumber(opts ...NumberOptFunc) *Number

NewNumber creates a new number type including the default Symbols table and default number format. You should only create one type and reuse the formatter anywhere else.

func (*Number) FmtFloat64

func (no *Number) FmtFloat64(w io.Writer, f float64) (int, error)

FmtFloat64 formats a float value, does internal maybe incorrect rounding. Thread safe

func (*Number) FmtInt64

func (no *Number) FmtInt64(w io.Writer, i int64) (int, error)

FmtInt64 formats an integer according to the format pattern. Thread safe

func (*Number) FmtNumber

func (no *Number) FmtNumber(w io.Writer, sign int, intgr int64, prec int, frac int64) (int, error)

FmtNumber formats a number according to the number format. Internal rounding will be applied. Returns the number bytes written or an error. Thread safe. For more details please see the interface documentation.

func (*Number) GetFormat

func (no *Number) GetFormat(isNegative bool) (format, error)

GetFormat parses the pattern depended if we have a negative value or not. Use this function only for debugging purposes. NOT Thread safe.

func (*Number) NOptions

func (no *Number) NOptions(opts ...NumberOptFunc) (previous NumberOptFunc)

NOptions applies number options and returns the last applied previous option function. For more details please read here http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html This function is thread safe.

type NumberFormatter

type NumberFormatter interface {
	// FmtNumber formats a number according to the number format of the
	// locale. i and frac represents a floating point number splitted in their
	// integer parts. Only i can be negative. Frac must always be positive. Sign
	// must be either -1 or +1. If sign is 0 the prefix will be guessed
	// from i. If sign and i are 0 function must return ErrCannotDetectMinusSign.
	// If sign is incorrect from i, sign will be adjusted to the prefix of i.
	// Prec specifies the overall precision of frac. E.g. your number is 0.0169
	// and prec is 4 then frac would be 169. Due to the precision the formatter
	// does know to add a leading zero. If prec is shorter than the length of
	// frac then prec will be adjusted to the frac length.
	FmtNumber(w io.Writer, sign int, i int64, prec int, frac int64) (int, error)
	// FmtInt formats an integer according to the format pattern.
	FmtInt64(w io.Writer, i int64) (int, error)
	// FmtFloat64 formats a float value, does internal maybe incorrect rounding.
	FmtFloat64(w io.Writer, f float64) (int, error)
}

NumberFormatter knows locale specific format properties about a currency/number.

var DefaultNumber NumberFormatter

DefaultNumber default formatter for default locale en-US

type NumberOptFunc

type NumberOptFunc func(*Number) NumberOptFunc

NumberOptFunc applies options to the Number struct. To read more about the recursion pattern: http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html

func NumberFormat

func NumberFormat(f string, s ...Symbols) NumberOptFunc

NumberFormat applies a format to a Number. If you do not have set the second argument Symbols (will be merge into) then the default Symbols will be used. Only one second argument is supported. If format is empty, fallback to the default format.

func NumberSymbols

func NumberSymbols(s Symbols) NumberOptFunc

NumberSymbols sets the Symbols tables. The argument will be merged into the default Symbols table

type Symbols

type Symbols struct {
	Decimal                rune // used
	Group                  rune // used
	List                   rune
	PercentSign            rune
	CurrencySign           rune
	PlusSign               rune // used
	MinusSign              rune // used
	Exponential            rune
	SuperscriptingExponent rune
	PerMille               rune
	Infinity               rune
	Nan                    []byte // used
}

Symbols general symbols used when formatting. Some are unused because @todo

func NewSymbols

func NewSymbols(syms ...Symbols) Symbols

NewSymbols creates a new non-pointer Symbols type with the pre-filled default symbol table. Use arguments to override the default symbols.

func (*Symbols) Merge

func (s *Symbols) Merge(from Symbols)

Merge merges one Symbols into another ignoring empty values in the argument Symbols struct.

func (Symbols) String

func (s Symbols) String() string

String human friendly printing. Shows also the default symbol table ;-)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL