bojanz / currency

Currency handling for Go.

Home Page:https://pkg.go.dev/github.com/bojanz/currency

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why does this invalid price not give an error?

curiosport opened this issue · comments

I would expect both of these instructions to raise an error because dollars use only 2 digits and yen does not use any digits.

amount, err := formatter.Parse("12.433356", "USD")
amount, err := formatter.Parse("12.433356", "JPY")
package main

import (
	"fmt"

	"github.com/bojanz/currency"
)

func main() {
	digits, _ := currency.GetDigits("USD")
	fmt.Println(fmt.Sprintf("USD has %d digits", digits))

	locale := currency.NewLocale("en_us")
	formatter := currency.NewFormatter(locale)

	fmt.Println(fmt.Sprintf("But it works with more than %d digits", digits))
	amount, err := formatter.Parse("12.433356", "USD")
	fmt.Println(err, amount)
}

Output:

USD has 2 digits
But it works with more than 2 digits
<nil> 12.433356 USD

Is there some reason or feature I'm missing?

Because as far as we're concerned those amounts are not invalid.

You will often find examples of price amounts with more digits than what the currency specifies. An extra digit for tax calculation reasons (EU VAT), or for unit prices of items sold in large quantities, or for certain product categories (gasoline in the US).

Other CLDR-powered NumberFormatters (PHP, Java) also allow parsing such amounts without errors. So if you have a need to be more strict, then that kind of check is best implemented on top of the existing logic (e.g. after Parse() returns).