go-money 實現貨幣運算的金標準

在進行金融領域的軟件開發時,貨幣值的精確表示和操作至關重要。由於浮點數帶來的精度問題,傳統的處理方式經常導致數值上的細微誤差。針對這一問題,go-money包提供了基於 Go 語言的解決方案,實現了 Fowler 的貨幣模式。

本文將深入解析go-money包,演示其具體的使用方式,並通過豐富的示例讓您掌握如何在 Go 項目中實現精確的貨幣計算。

起步:安裝 go-money

要使用go-money,首先需要安裝該包。在命令行中輸入以下命令來獲取包:

$ go get github.com/Rhymond/go-money

初始化

go-money允許通過兩種方式初始化貨幣值:

import "github.com/Rhymond/go-money"

// 使用最小單位初始化(100代表1英鎊)
pound := money.New(100, money.GBP)

// 使用浮點數直接初始化
quarterEuro := money.NewFromFloat(0.25, money.EUR)

go-money要求使用 ISO 4217 貨幣代碼來設定貨幣類型,併爲所有 ISO 4217 標準貨幣代碼提供了常量。

貨幣比較

go-money提供了一系列貨幣值比較功能,包括:

比較操作必須在相同的貨幣單位之間進行。

pound := money.New(100, money.GBP)
twoPounds := money.New(200, money.GBP)
twoEuros := money.New(200, money.EUR)

// 比較英鎊數額
pound.GreaterThan(twoPounds) // 返回 false, nil
pound.LessThan(twoPounds) // 返回 true, nil
twoPounds.Equals(twoEuros) // 返回 false, error: Currencies don't match
twoPounds.Compare(pound) // 返回 1, nil
pound.Compare(twoPounds) // 返回 -1, nil
pound.Compare(pound) // 返回 0, nil
pound.Compare(twoEuros) // 返回 pound.amount, ErrCurrencyMismatch

斷言

go-money還提供了以下斷言方法:

pound := money.New(100, money.GBP)

// 斷定是否爲零
result := pound.IsZero() // 返回 false

// 斷定是否爲正值
pound.IsPositive() // 返回 true

// 斷定是否爲負值
pound.IsNegative() // 返回 false

基本運算

go-money支持以下基礎貨幣運算:

// 加法
pound := money.New(100, money.GBP)
result, err := pound.Add(twoPounds) // 返回 £3.00, nil

// 減法
result, err = pound.Subtract(twoPounds) // 返回 -£1.00, nil

// 乘法
result = pound.Multiply(2) // 返回 £2.00

// 絕對值
pound = money.New(-100, money.GBP)
result = pound.Absolute() // 返回 £1.00

// 負值
result = pound.Negative() // 返回 -£1.00

分配運算

// 分割
pound := money.New(100, money.GBP)
parties, err := pound.Split(3)

// 分割後的每一份
parties[0].Display() // 輸出 £0.34
parties[1].Display() // 輸出 £0.33
parties[2].Display() // 輸出 £0.33

// 分配
// Allocate是可變參數函數,可以接收切片(int[]{33, 33, 33}...)或逗號分隔的整數
parties, err = pound.Allocate(33, 33, 33)

// 分配後的每一份
parties[0].Display() // 輸出 £0.34
parties[1].Display() // 輸出 £0.33
parties[2].Display() // 輸出 £0.33

格式化

使用Display()AsMajorUnits()方法可以將貨幣值進行格式化。

// 使用 Display() 格式化
money.New(123456789, money.EUR).Display() // 輸出 €1,234,567.89

// 使用 AsMajorUnits() 格式化爲浮點數表示的金額值
money.New(123456789, money.EUR).AsMajorUnits() // 輸出 1234567.89

在這些示例中,我們看到go-money包如何提供了一種簡便的方式來處理貨幣值,從而避免了傳統浮點數操作中常見的精度問題。

綜上,通過深入理解和學習go-money的使用方法和示例,您可以在 Go 語言開發中,輕鬆實現精確的貨幣計算和操作,確保金融領域軟件的高質量和可靠性。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/CUjouJ9cgj7W_5Upeu7hsw