golang 每日一庫之 shopspring-decimal

shopspring/decimal 是一個用於處理任意精度十進制浮點數的 Go 語言庫,通常用於金融計算、貨幣相關計算等場景。標準的 float64 類型可能無法滿足精確度要求,因爲浮點數的表示方式是近似的,特別是在進行累加、除法和精確比較時可能會導致舍入誤差。

shopspring/decimal 提供了一個高精度的十進制類型 decimal.Decimal,它確保在進行數學運算時不丟失精度。這個庫特別適合用於需要嚴格計算精度的場景,例如處理貨幣、財務、稅務等領域中的數值計算。

1. 安裝 shopspring/decimal

要使用 shopspring/decimal,首先需要安裝它。可以使用以下命令來安裝:

go get github.com/shopspring/decimal

2. 基本用法

創建 decimal.Decimal 值

package main

import (
    "fmt"
    "github.com/shopspring/decimal"
)

func main() {
    // 從字符串創建 Decimal
    d1, err := decimal.NewFromString("123.456")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    // 從浮動數創建 Decimal
    d2 := decimal.NewFromFloat(123.456)

    // 從整數創建 Decimal
    d3 := decimal.NewFromInt(123)

    fmt.Println("d1:", d1)
    fmt.Println("d2:", d2)
    fmt.Println("d3:", d3)
}

3. 常用操作

shopspring/decimal 提供了多種操作方法,允許進行加、減、乘、除、比較等常見的數學運算。

加法、減法、乘法、除法

package main

import (
    "fmt"
    "github.com/shopspring/decimal"
)

func main() {
    d1, _ := decimal.NewFromString("10.5")
    d2, _ := decimal.NewFromString("2.3")

    sum := d1.Add(d2)       // 加法
    difference := d1.Sub(d2) // 減法
    product := d1.Mul(d2)    // 乘法
    quotient := d1.Div(d2, 2) // 除法 (第二個參數是精度)

    fmt.Println("Sum:", sum)
    fmt.Println("Difference:", difference)
    fmt.Println("Product:", product)
    fmt.Println("Quotient:", quotient)
}

比較

你可以使用以下方法比較 Decimal 值:

package main

import (
    "fmt"
    "github.com/shopspring/decimal"
)

func main() {
    d1, _ := decimal.NewFromString("10.5")
    d2, _ := decimal.NewFromString("2.3")

    fmt.Println("d1 == d2:", d1.Equal(d2))
    fmt.Println("d1 < d2:", d1.LessThan(d2))
    fmt.Println("d1 > d2:", d1.GreaterThan(d2))
}

設置精度

在進行除法等運算時,你可能需要指定精度(即小數點後的位數),可以使用 decimal.Div 方法指定精度。

package main

import (
    "fmt"
    "github.com/shopspring/decimal"
)

func main() {
    d1, _ := decimal.NewFromString("10.0")
    d2, _ := decimal.NewFromString("3.0")

    // 除法,保留 2 位小數
    result := d1.Div(d2, 2)

    fmt.Println("Result:", result) // 結果是 3.33
}

4. 常用方法

package main

import (
    "fmt"
    "github.com/shopspring/decimal"
)

func main() {
    d, _ := decimal.NewFromString("-123.456")

    // 獲取絕對值
    abs := d.Abs()
    fmt.Println("Absolute Value:", abs)

    // 四捨五入到兩位小數
    rounded := d.Round(2)
    fmt.Println("Rounded Value:", rounded)

    // 轉爲字符串
    str := d.String()
    fmt.Println("String Representation:", str)

    // 轉爲 float64
    floatValue := d.Float64()
    fmt.Println("Float64 Value:", floatValue)
}

5. 爲何使用 shopspring/decimal

6. 應用場景

7. 總結

shopspring/decimal 是一個強大且高精度的 Go 庫,解決了標準浮動點數類型在精度計算中的問題,特別適用於需要精確計算的場景,如金融、會計、電商等。如果你的應用需要處理精確的貨幣計算、利率計算等,這個庫是非常合適的選擇。

通過它提供的精確的數學運算,你可以避免傳統 float64 類型在處理財務、稅務等領域中的常見誤差,確保計算結果的準確性。

標題:golang 每日一庫之 shopspring/decimal
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/01/14/1736839343255.html

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