skip to content
Alvin Lucillo

Representing currency amount in Go

/ 1 min read

💻 Tech

It’s common to represent currency amount as its smallest unit in DB like cents for dollars and fils for dinars. For example, 1.24 USD is represented as 124 cents because 1 dollar is 100 cents and 24 cents is 24 cents. 5.678 KWD is represented as 5678 fils because 1 dinar is 1000 fils and 678 fils is 678 fils. Once you have the smallest currency unit from the DB, you can represent it in Go with shopspring decimal package. Here’s an example:

exp := -2 // 2 decimal places for currencies like USD
amountInSmallestUnit := 124 // the smallest unit of 1.24 USD

d := decimal.New(int64(amountInSmallestUnit), int32(exp)) // 1.24 USD