A currency computations package.

webgo gopher

build coverage report maintainability godoc awesome-go

Currency v1.0.0

Currency package helps you do currency computations accurately, by avoiding peddling. The Currency struct holds all the data required to define a currency.

type Currency struct {
	// Code represents the international currency code
	Code string
	// Symbol is the respective currency symbol
	Symbol string
	// Main represents the main value of the currency
	Main int
	// Fractional represents the fractional/sub unit of the currency
	Fractional uint
	// FUName is the name of the fractional/sub unit of the currency. e.g. paise
	FUName string
	// FUShare represents the no.of fractional/sub units that make up 1 main unit. e.g. ₹1 = 100 paise
	// Number of fractional units that make up 1 unit of the main value
	FUShare uint
}

New(main int, fractional int, code, symbol string, funame string, fushare uint)

New returns a pointer of currency instance created based on the values provided

main - Main/Super unit of the currency
fractional - Subunit/fractional unit of the currency
code - is the currency code according to [ISO 4217 specification](https://en.wikipedia.org/wiki/ISO_4217)
symbol - Unicode symbol of the currency
funame - Name of the fractional/sub unit
fushare - Number of fractional/sub units that make up 1 unit of the main/super unit

IMPORTANT! Fractional unit can be negative only when the main value is 0. If the main value is not 0, fractional unit's negative sign is ignored.

Parsers & convenience methods

  1. NewFractional(fractional int, symbol string, fulabel string, fushare uint) returns a currency struct instance, given a currency's total value represented by the fractional unit
  2. ParseString(value string, code, symbol string, fulabel string, fushare uint) returns a currency struct instance, given a currency value represented as string
  3. ParseFloat64(value float64, code, symbol string, funame string, fushare uint) returns a currency struct instance, given a currency value represented in float64

Computational methods

IMPORTANT: Computation is supported only between same type of currencies (i.e. currency codes should be same)

  1. c1.Add(c2 currency) add c2 to c1, and update c1
  2. c1.AddInt(main int, fractional int) add the currency equivalent of the main & fractional int to c1
  3. c1.Subtract(c2 currency) subtract c2 from c1, and update c1
  4. c1.SubtractIn(main int, fractional int) subtract the currency equivalent of the main & fractional int from c1
  5. c1.Multiply(n int) multiply c1 by n, where n is an integer
  6. c1.MultiplyFloat64(n float64) multiply c1 by n, where n is a float64 value
  7. c1.UpdateWithFractional(ftotal int) would update the the value of c1, where ftotal is the total value of the currency in fractional unit. e.g. INR, UpdateWithFractional(100) would set the main value as 1 and fractional unit as 0
  8. c1.FractionalTotal() int returns the total value of the currency in its fractional unit. e.g. INR, if the Main value is 1 and fractional unit is 0, it would return 100, i.e. 100 paise
  9. c1.Percent(n float64) currency returns a new currency instance which is n percentage of c1
  10. c1.Divide(n int, retain bool)[]currency, ok returns a slice of currency of size n. ok if returned as true means the currency value was perfectly divisible by n. If retain is true, then c1 will have the remainder value after dividing otherwise it is distributed among the returned currencies.

Why does Divide(n int, retain bool) return a slice of currencies?

Divide unlike other operations, cannot be rounded off. If it is rounded, it would result in currency peddling.

e.g. ₹1/- (INR 1) is to be divided by 3. There are 2 options of dividing this by 3.

1. Set 33 paise per split, and retain the remaining 1 paise at source. (`Divide(n, true)`)

2. Set 1 of the split with an extra value, i.e. 34 + 33 + 33. (`Divide(n, false)`)

Multiple currency representations

  1. c1.String(prefixSymbol bool), returns a string representation of the currency value. Returns string prefixed by its respective symbol if prefixSymbol is true
  2. c1.Float64(), returns a float64 representation of the currency value

Benchmarks

How to run?

$ go test -bench=.

Results when run on a MacBook Pro (13-inch, Early 2015), CPU: 2.7 GHz Intel Core i5, RAM: 8 GB 1867 MHz DDR3, Graphics: Intel Iris Graphics 6100 1536 MB

BenchmarkNew-4                    	20000000	        67.3 ns/op
BenchmarkNewFractional-4          	20000000	        65.9 ns/op
BenchmarkParseFloat64-4           	20000000	        87.4 ns/op
BenchmarkParseString-4            	 3000000	       544 ns/op
BenchmarkString-4                 	10000000	       211 ns/op
BenchmarkStringNoPrefix-4         	10000000	       164 ns/op
BenchmarkFloat64-4                	2000000000	         0.34 ns/op
BenchmarkFractionalTotal-4        	2000000000	         0.33 ns/op
BenchmarkUpdateWithFractional-4   	100000000	        10.3 ns/op
BenchmarkAdd-4                    	100000000	        20.8 ns/op
BenchmarkAddInt-4                 	100000000	        18.9 ns/op
BenchmarkSubtract-4               	100000000	        21.2 ns/op
BenchmarkSubtractInt-4            	100000000	        18.3 ns/op
BenchmarkMultiply-4               	100000000	        16.2 ns/op
BenchmarkMultiplyFloat64-4        	50000000	        30.1 ns/op
BenchmarkPercent-4                	20000000	        67.1 ns/op
BenchmarkDivide-4                 	10000000	       155 ns/op

References

  1. Ref - Sub unit or fractional unit
  2. Ref - Currencies - about currencies
  3. Non-decimal sub unit in currencies are only used by 2 countries today. These are getting phased out.

IMPORTANT! This package does not support sub units which are not a power of 10. Nor does it support currencies with more than 1 sub unit

The gopher

The gopher used here was created using Gopherize.me. Deal with currency professionally just like this gopher!

Owner
Kamaleshwar
Let's fix this planet, one line of code at a time.
Kamaleshwar
Similar Resources

Simple user currency module that uses JSON.

UserCurrency Simple user currency module that uses JSON. Install go get github.com/NeutronX-dev/UserCurrency Functions func UserCurrency.Read(path_to

Nov 23, 2021

Go client for the Foreign exchange rates and currency conversion API moneybag

fixer Go client for Fixer.io (Foreign exchange rates and currency conversion API) You need to register for a free access key if using the default Fixe

Nov 25, 2021

Prosper - General app launcher with support for translation, calc, currency and unit conversion.

Prosper - General app launcher with support for translation, calc, currency and unit conversion.

Prosper Description General app launcher with support for translation, calc, currency and unit conversion. Global shortcut is Option (Alt) + Space Fea

Dec 6, 2022

Coinbase - You can use this to retrieve the current price for an crypto currency

whats-this You can use this to retrieve the current price for an crypto currency

Sep 29, 2022

A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities.

ozzo-dbx Summary Description Requirements Installation Supported Databases Getting Started Connecting to Database Executing Queries Binding Parameters

Dec 31, 2022

Go Package Manager (gopm) is a package manager and build tool for Go.

🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 In favor of Go Modules Proxy since Go 1.11, this pr

Dec 14, 2022

Package set is a small wrapper around the official reflect package that facilitates loose type conversion and assignment into native Go types.

Package set is a small wrapper around the official reflect package that facilitates loose type conversion and assignment into native Go types. Read th

Dec 27, 2022

Go package providing simple database and server interfaces for the CSV files produced by the sfomuseum/go-libraryofcongress package

Go package providing simple database and server interfaces for the CSV files produced by the sfomuseum/go-libraryofcongress package

go-libraryofcongress-database Go package providing simple database and server interfaces for the CSV files produced by the sfomuseum/go-libraryofcongr

Oct 29, 2021

A package for running subprocesses in Go, similar to Python's subprocesses package.

A package for running subprocesses in Go, similar to Python's subprocesses package.

Jul 28, 2022

Utility to restrict which package is allowed to import another package.

go-import-rules Utility to restrict which package is allowed to import another package. This tool will read import-rules.yaml or import-rules.yml in t

Jan 7, 2022

A package for running subprocesses in Go, similar to Python's subprocesses package.

Subprocesses Spawn subprocesses in Go. Sanitized mode package main import ( "log" "github.com/estebangarcia21/subprocess" ) func main() { s := s

Jul 28, 2022

An errors package optimized for the pkg/errors package

An errors package optimized for the pkg/errors package

errors An errors package optimized for the pkg/errors package Use Download and install go get github.com/dobyte/errors API // New Wrapping for errors.

Mar 2, 2022

Wmi - One hot Go WMI package. Package wmi provides an interface to WMI. (Windows Management Instrumentation)

wmi Package wmi provides an interface to WMI. (Windows Management Instrumentation) Install go get -v github.com/moonchant12/wmi Import import "github.

Apr 22, 2022

Elastos.ELA.Rosetta.API - How to write a Rosetta server and use either the Client package or Fetcher package to communicate

Examples This folder demonstrates how to write a Rosetta server and how to use e

Jan 17, 2022

A simple errors package that dynamically prepends the package name.

errors 🍪 Buy me a cookie What is this? A simple errors package that dynamically prepends the package name. How to install Open a terminal and run the

Jan 16, 2022

Example-go-install - A package aims to demonstrate how libraries / commands should be organized in a go package

Example-go-install - A package aims to demonstrate how libraries / commands should be organized in a go package

Jan 27, 2022

Go package providing opinionated tools and methods for working with the `aws-sdk-go/service/cloudfront` package.

go-aws-cloudfront Go package providing opinionated tools and methods for working with the aws-sdk-go/service/cloudfront package. Documentation Tools $

Feb 2, 2022

Fetch-npm-package - A small utility that can be used to fetch a given version of a NPM package

Use fetch-npm-package package version output-dir E.g. fetch-npm-package is

May 21, 2022
Comments
  • [minor] implemented fmt.Formatter interface

    [minor] implemented fmt.Formatter interface

    • 's' verb would produce the full currency string along with its symbol. equivalent to c.String(true)
    • 'd' verb would produce the main integer part of the currency, without the symbol
    • 'm' verb would produce the fractional integer part of the currency, without the symbol
    • 'f' verb would produce the full currency string without its symbol. equivalent to c.String(false)
    • 'y' verb would produce the currency symbol alone
  • Implement fmt.Stringer.

    Implement fmt.Stringer.

    Hi @bnkamalesh, thank you for this awesome package. It would be really nice if currency.Currency implements fmt.Stringer interface. At this moment it has a string method, but it has a signature like below:

    func (c *Currency) String(prefixSymbol bool) string
    

    To implement fmt.Stringer the string method must have the signature:

    func (c *Currency) String() string
    

    If the Currency type implements fmt.Stringer, we will not need to call c.String(true|false), every-time we want to get the formatted string output.

    So I propose, the Currency should have method signatures like this

    func (c *Currency) SetSymbol(symbol string)
    func (c *Currency) String() string
    

    or,

    func (c *Currency) PrefixSymbol(symbol string) string
    func (c *Currency) String() string
    

    This is just a concept, I am confident that you will find even better way out.

Currency handling for Go.

currency Handles currency amounts, provides currency information and formatting. Powered by CLDR v38, in just ~30kb of data. Backstory: https://bojanz

Jan 3, 2023
Go package for dealing with EU VAT. Does VAT number validation & rates retrieval.

Package vat Package for validating VAT numbers & retrieving VAT rates in Go. Installation Use go get. go get github.com/dannyvankooten/vat Then impor

Dec 6, 2022
Package to easily consume the Dolarpy API in golang.

dolarpy-go Package to easily consume the Dolarpy API in golang. https://github.com/melizeche/dolarPy - by melizeche Install import "github.com/bitebai

Apr 11, 2022
Supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for the safe retrieval of the computation results.

Rendezvous The Rendezvous library supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for

Dec 29, 2021
money and currency formatting for golang

accounting - money and currency formatting for golang accounting is a library for money and currency formatting. (inspired by accounting.js) Quick Sta

Dec 21, 2022
Currency handling for Go.

currency Handles currency amounts, provides currency information and formatting. Powered by CLDR v38, in just ~30kb of data. Backstory: https://bojanz

Jan 3, 2023
A command line Crypto-currency ticker made using golang and WazirX Api
A command line Crypto-currency ticker made using golang and WazirX Api

░█████╗░██████╗░██╗░░░██╗██████╗░████████╗███████╗██╗░░██╗ ██╔══██╗██╔══██╗╚██╗░██╔╝██╔══██╗╚══██╔══╝██╔════╝╚██╗██╔╝ ██║░░╚═╝██████╔╝░╚████╔╝░██████╔

Feb 6, 2022
Go client for the Foreign exchange rates and currency conversion API 💰

fixer Go client for Fixer.io (Foreign exchange rates and currency conversion API) You need to register for a free access key if using the default Fixe

Nov 14, 2022
Dec 29, 2022
A reward-based pseudo-currency system built exclusively for IIT Kanpur campus junta.

IITK Coin IITK Coin is a reward-based pseudo-currency system for the IIT Kanpur campus junta. Detailed vision and regulation rules of this currency ar

Nov 29, 2022