Install the decimal library
masterTo add the decimal library to your Go project, run the following command:
go get github.com/shopspring/decimalrepository·master·Indexed 27 days ago
https://github.com/shopspring/decimalA Go library for arbitrary-precision fixed-point decimal numbers designed for correctness in financial applications. It provides immutable Decimal types to prevent floating-point errors, supporting a wide range of arithmetic operations, rounding strategies, trigonometric functions, and natural exponents/logarithms. Includes NullDecimal for nullable database fields and supports Go version >=1.10.
To add the decimal library to your Go project, run the following command:
go get github.com/shopspring/decimalThe decimal library provides arbitrary-precision fixed-point decimal numbers. It is designed for correctness, particularly for financial applications, by ensuring that arithmetic operations like addition, subtraction, and multiplication do not lose precision. All methods return a new Decimal value and do not modify the original receiver.
package main
import (
"fmt"
"github.com/shopspring/decimal"
)
func main() {
price, err := decimal.NewFromString("136.02")
if err != nil {
panic(err)
}
quantity := decimal.NewFromInt(3)
fee, _ := decimal.NewFromString(".035")
taxRate, _ := decimal.NewFromString(".08875")
subtotal := price.Mul(quantity)
preTax := subtotal.Mul(fee.Add(decimal.NewFromFloat(1)))
total := preTax.Mul(taxRate.Add(decimal.NewFromFloat(1)))
fmt.Println("Subtotal:", subtotal) // Subtotal: 408.06
fmt.Println("Pre-tax:", preTax) // Pre-tax: 422.3421
fmt.Println("Taxes:", total.Sub(preTax)) // Taxes: 37.482861375
fmt.Println("Total:", total) // Total: 459.824961375
fmt.Println("Tax rate:", total.Sub(preTax).Div(preTax)) // Tax rate: 0.08875
}The following global variables control the behavior of the decimal package:
DivisionPrecision (int): The number of decimal places in the result when a division doesn't divide exactly. Default is 16.PowPrecisionNegativeExponent (int): The maximum precision (digits after decimal point) when calculating decimal power with a negative exponent. Default is 16.MarshalJSONWithoutQuotes (bool): If true, decimals are marshaled as JSON numbers instead of strings. Warning: This can lead to precision loss in consumers like JavaScript.TrimTrailingZeros (bool): If true, trailing zeros are removed from string representations (e.g., 2.00 becomes 2). Default is true.UseScientificNotation (bool): If true, scientific notation is used for strings with negative precision. Default is false.ExpMaxIterations (int): Maximum iterations for the ExpHullAbrham natural exponent calculation. Default is 1000.>=1.10Use these methods for boolean comparisons between Decimal values:
Equal(d2): Returns true if d == d2.GreaterThan(d2): Returns true if d > d2.GreaterThanOrEqual(d2): Returns true if d >= d2.LessThan(d2): Returns true if d < d2.LessThanOrEqual(d2): Returns true if d <= d2.Determine the sign of a Decimal using:
Sign(): Returns -1 if d < 0, 0 if d == 0, or +1 if d > 0.IsPositive(): Returns true if d > 0.IsNegative(): Returns true if d < 0.IsZero(): Returns true if d == 0.IsInteger(): Returns true if the decimal can be represented as an integer value.Convert Decimal to string representations:
String(): Returns the standard string representation.StringFixed(places int32): Returns a rounded fixed-point string with the specified number of digits after the decimal point.StringFixedBank(places int32): Returns a banker-rounded fixed-point string.StringFixedCash(interval uint8): Returns a Swedish/Cash rounded string using specific intervals (5, 10, 25, 50, 100). Panics if an invalid interval is provided.ScientificNotationString(): Returns the decimal in standard scientific notation.Access the underlying parts of a Decimal:
Exponent(): Returns the exponent (scale component) as int32.Coefficient(): Returns the coefficient as a *big.Int (returns a copy to prevent mutation).CoefficientInt64(): Returns the coefficient as an int64. Note: result is undefined if the coefficient exceeds int64 range.IntPart(): Returns the integer component as an int64.BigInt(): Returns the integer component as a *big.Int.Calculate trigonometric functions for a Decimal (arguments in radians):
Atan(): Arctangent.Sin(): Sine.Cos(): Cosine.Tan(): Tangent.For advanced mathematical operations, use the following methods:
ExpHullAbrham(overallPrecision uint32) (Decimal, error): Calculates the natural exponent ($e^d$) using the Hull-Abraham algorithm. It is faster for small precision values but slower for large ones.ExpTaylor(precision int32) (Decimal, error): Calculates the natural exponent ($e^d$) using Taylor series expansion. It is faster for large precision values.Ln(precision int32) (Decimal, error): Calculates the natural logarithm of d. Returns an error if d is negative or zero.Apply various rounding strategies to a Decimal:
Round(places int32): Rounds to the specified decimal places.RoundCeil(places int32): Rounds towards positive infinity.RoundFloor(places int32): Rounds towards negative infinity.RoundUp(places int32): Rounds away from zero.RoundDown(places int32): Rounds towards zero.RoundBank(places int32): Banker's rounding (rounds to the nearest even number if equidistant).Truncate(precision int32): Truncates digits without rounding.Convert Decimal to standard Go numeric types:
BigFloat(): Returns the decimal as a *big.Float. Warning: may cause loss of precision.Rat(): Returns a rational number representation (*big.Rat).Float64(): Returns the nearest float64 and a boolean indicating if the conversion was exact.InexactFloat64(): Returns the nearest float64 without indicating exactness.