Rhymond/go-money

Use number of minor units in one major instead of a fraction

dzyanis opened this issue · 0 comments

I know that most majority of currencies have 100 minor units in one major or don't have a minor at all and it's okay to save their fraction (2, 0 or 3) and use them for converting:

func (f *Formatter) ToMajorUnits(amount int64) float64 {
	if f.Fraction == 0 {
		return float64(amount)
	}

	return float64(amount) / float64(math.Pow10(f.Fraction))
}

But my suggestion is to be more pragmatic and remember about non-decimal currency and etc:

  • Malagasy ariary (1 ariary = 5 iraimbilanja), Mauritanian ouguiya and etc.;
  • Old currencies: 1 Thaler = 36 Mariengroschen = 288 Pfennige;
  • Fictional currencies: 1 Galleon = 17 Sickles = 493 Knuts;
  • Cryptocurrencies: 1 BTC = 100'000'000 Satoshi

And if we use the number of minor units we can remove this math.Pow10 function and the result will look like:

func (f *Formatter) ToMajorUnits(amount int64) float64 {
	if f.Units == 0 {
		return float64(amount)
	}

	return float64(amount) / float64(f.Units)
}