### big.Int Addition Example Source: https://github.com/shopspring/decimal/blob/master/README.md Demonstrates the correct way to add two big.Int values, which involves creating a new big.Int and calling the Add method. Incorrect usage can lead to unexpected modifications of existing variables. ```go z := new(big.Int).Add(x, y) ``` -------------------------------- ### Perform Decimal Arithmetic in Go Source: https://github.com/shopspring/decimal/blob/master/README.md Demonstrates basic usage of the decimal library for financial calculations, including initialization from strings and integers, and arithmetic operations. ```go 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 } ``` -------------------------------- ### Boolean Comparison (GreaterThan, LessThan, etc.) Source: https://context7.com/shopspring/decimal/llms.txt Shows how to use boolean comparison methods like GreaterThan, LessThan, GreaterThanOrEqual, and LessThanOrEqual for relational checks between decimal numbers. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.RequireFromString("10.5") b := decimal.RequireFromString("20.0") c := decimal.RequireFromString("10.5") fmt.Println(a.GreaterThan(b)) // Output: false fmt.Println(a.LessThan(b)) // Output: true fmt.Println(a.GreaterThanOrEqual(c)) // Output: true fmt.Println(a.LessThanOrEqual(c)) // Output: true } ``` -------------------------------- ### Create Decimal from Coefficient and Exponent - New Source: https://context7.com/shopspring/decimal/llms.txt Constructs a Decimal value programmatically using a coefficient and an exponent, representing the number as `coefficient * 10^exponent`. Useful for precise mathematical construction. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // 12345 * 10^(-4) = 1.2345 d1 := decimal.New(12345, -4) fmt.Println(d1.String()) // Output: 1.2345 // 100 * 10^2 = 10000 d2 := decimal.New(100, 2) fmt.Println(d2.String()) // Output: 10000 // -500 * 10^(-2) = -5.00 d3 := decimal.New(-500, -2) fmt.Println(d3.String()) // Output: -5 } ``` -------------------------------- ### Initialize Decimals from BigInt and BigRat Source: https://context7.com/shopspring/decimal/llms.txt Create Decimals from Go's math/big types. NewFromBigRat allows specifying rounding precision for rational numbers. ```go package main import ( "fmt" "math/big" "github.com/shopspring/decimal" ) func main() { // From big.Int with exponent bigInt := big.NewInt(12345) d1 := decimal.NewFromBigInt(bigInt, -2) fmt.Println(d1.String()) // Output: 123.45 // From big.Rat with precision rat := big.NewRat(1, 3) // 1/3 d2 := decimal.NewFromBigRat(rat, 4) fmt.Println(d2.String()) // Output: 0.3333 rat2 := big.NewRat(4, 5) // 4/5 d3 := decimal.NewFromBigRat(rat2, 1) fmt.Println(d3.String()) // Output: 0.8 } ``` -------------------------------- ### Directional Rounding (RoundUp, RoundDown, RoundCeil, RoundFloor) Source: https://context7.com/shopspring/decimal/llms.txt Demonstrates directional rounding methods: RoundUp (away from zero), RoundDown (towards zero), RoundCeil (towards positive infinity), and RoundFloor (towards negative infinity). ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { pos := decimal.RequireFromString("1.234") neg := decimal.RequireFromString("-1.234") // RoundUp - away from zero fmt.Println(pos.RoundUp(2).String()) // Output: 1.24 fmt.Println(neg.RoundUp(2).String()) // Output: -1.24 // RoundDown - towards zero fmt.Println(pos.RoundDown(2).String()) // Output: 1.23 fmt.Println(neg.RoundDown(2).String()) // Output: -1.23 // RoundCeil - towards +infinity fmt.Println(pos.RoundCeil(2).String()) // Output: 1.24 fmt.Println(neg.RoundCeil(2).String()) // Output: -1.23 // RoundFloor - towards -infinity fmt.Println(pos.RoundFloor(2).String()) // Output: 1.23 fmt.Println(neg.RoundFloor(2).String()) // Output: -1.24 } ``` -------------------------------- ### Decimal Comparison (Cmp, Equal) Source: https://context7.com/shopspring/decimal/llms.txt Explains Cmp for comparing two decimals (-1, 0, or 1) and Equal for checking mathematical equality. Compare is an alias for Cmp. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.RequireFromString("10.5") b := decimal.RequireFromString("10.50") c := decimal.RequireFromString("11.0") // Cmp returns -1, 0, or 1 fmt.Println(a.Cmp(b)) // Output: 0 (equal) fmt.Println(a.Cmp(c)) // Output: -1 (a < c) fmt.Println(c.Cmp(a)) // Output: 1 (c > a) // Equal checks mathematical equality fmt.Println(a.Equal(b)) // Output: true (10.5 == 10.50) fmt.Println(a.Equal(c)) // Output: false } ``` -------------------------------- ### Configure Global Decimal Settings Source: https://context7.com/shopspring/decimal/llms.txt Adjust global variables like DivisionPrecision, MarshalJSONWithoutQuotes, TrimTrailingZeros, and PowPrecisionNegativeExponent to control library behavior. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // DivisionPrecision - decimal places for division (default: 16) decimal.DivisionPrecision = 8 result := decimal.NewFromInt(1).Div(decimal.NewFromInt(3)) fmt.Println(result.String()) // Output: 0.33333333 // MarshalJSONWithoutQuotes - serialize as number (default: false) decimal.MarshalJSONWithoutQuotes = true // TrimTrailingZeros - trim zeros in String() (default: true) decimal.TrimTrailingZeros = false d := decimal.RequireFromString("10.50") fmt.Println(d.String()) // Output: 10.50 (without trimming: 10.5 with trimming) // PowPrecisionNegativeExponent - precision for negative exponents (default: 16) decimal.PowPrecisionNegativeExponent = 20 pow, _ := decimal.NewFromFloat(2.0).PowInt32(-10) fmt.Println(pow.String()) // Uses 20 decimal places } ``` -------------------------------- ### Copy and Shift Decimal Values Source: https://context7.com/shopspring/decimal/llms.txt Use Copy to create a deep copy of a decimal. Use Shift to multiply or divide by powers of 10 by adjusting the exponent. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { original := decimal.RequireFromString("123.45") // Create a copy copied := original.Copy() fmt.Println(copied.String()) // Output: 123.45 // Shift left (multiply by 10^n) shifted := original.Shift(2) fmt.Println(shifted.String()) // Output: 12345 // Shift right (divide by 10^n) shifted2 := original.Shift(-2) fmt.Println(shifted2.String()) // Output: 1.2345 } ``` -------------------------------- ### Create Decimal from Floats - NewFromFloat, NewFromFloat32 Source: https://context7.com/shopspring/decimal/llms.txt Converts float64 and float32 values to Decimal. Be aware that the original float may already contain precision errors. `NewFromFloatWithExponent` allows for faster conversion with an explicit exponent. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // From float64 d1 := decimal.NewFromFloat(123.456) fmt.Println(d1.String()) // Output: 123.456 d2 := decimal.NewFromFloat(-0.0001) fmt.Println(d2.String()) // Output: -0.0001 // From float32 d3 := decimal.NewFromFloat32(3.14159) fmt.Println(d3.String()) // Output: 3.14159 // With explicit exponent for faster conversion d4 := decimal.NewFromFloatWithExponent(123.456, -2) fmt.Println(d4.String()) // Output: 123.46 } ``` -------------------------------- ### Initialize Decimals from Strings Source: https://context7.com/shopspring/decimal/llms.txt Use RequireFromString to create a Decimal from a string, which panics on invalid input. This is ideal for constants or test scenarios where input validity is guaranteed. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // Safe to use when you know the string is valid price := decimal.RequireFromString("99.99") taxRate := decimal.RequireFromString("0.0825") fmt.Println(price.String()) // Output: 99.99 fmt.Println(taxRate.String()) // Output: 0.0825 } ``` -------------------------------- ### Create Decimal from Integers - NewFromInt, NewFromInt32, NewFromUint64 Source: https://context7.com/shopspring/decimal/llms.txt Creates Decimal values from native Go integer types without precision loss. Suitable for whole number representations. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // From int64 d1 := decimal.NewFromInt(123) fmt.Println(d1.String()) // Output: 123 d2 := decimal.NewFromInt(-10) fmt.Println(d2.String()) // Output: -10 // From int32 d3 := decimal.NewFromInt32(456) fmt.Println(d3.String()) // Output: 456 // From uint64 d4 := decimal.NewFromUint64(18446744073709551615) fmt.Println(d4.String()) // Output: 18446744073709551615 } ``` -------------------------------- ### Integrate Decimals with Databases Source: https://context7.com/shopspring/decimal/llms.txt The library implements database/sql Scanner and Valuer interfaces for direct database interaction. ```go package main import ( "database/sql" "fmt" "github.com/shopspring/decimal" _ "github.com/lib/pq" // PostgreSQL driver ) type Order struct { ID int Total decimal.Decimal } func main() { // Example database operations (pseudocode - requires actual DB) db, _ := sql.Open("postgres", "connection_string") defer db.Close() // Insert total := decimal.RequireFromString("199.99") _, _ = db.Exec("INSERT INTO orders (total) VALUES ($1)", total) // Query var order Order row := db.QueryRow("SELECT id, total FROM orders WHERE id = $1", 1) _ = row.Scan(&order.ID, &order.Total) fmt.Println(order.Total.String()) // Output: 199.99 } ``` -------------------------------- ### Creating Decimals - NewFromInt / NewFromInt32 / NewFromUint64 Source: https://context7.com/shopspring/decimal/llms.txt Creates a Decimal from integer types without any precision loss. Useful when working with whole numbers or converting from integer-based representations. ```APIDOC ## Creating Decimals - NewFromInt / NewFromInt32 / NewFromUint64 ### Description Creates a Decimal from integer types without any precision loss. Useful when working with whole numbers or converting from integer-based representations. ### Method - `NewFromInt(i int64) Decimal` - `NewFromInt32(i int32) Decimal` - `NewFromUint64(i uint64) Decimal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The created Decimal value. #### Response Example ```go // Example usage: d1 := decimal.NewFromInt(123) fmt.Println(d1.String()) // Output: 123 d3 := decimal.NewFromInt32(456) fmt.Println(d3.String()) // Output: 456 d4 := decimal.NewFromUint64(18446744073709551615) fmt.Println(d4.String()) // Output: 18446744073709551615 ``` ``` -------------------------------- ### Creating Decimals - New Source: https://context7.com/shopspring/decimal/llms.txt Creates a Decimal from a coefficient and exponent, where the value equals `coefficient * 10^exponent`. Useful for programmatic construction of decimal values. ```APIDOC ## Creating Decimals - New ### Description Creates a Decimal from a coefficient and exponent, where the value equals `coefficient * 10^exponent`. Useful for programmatic construction of decimal values. ### Method `New(coefficient int64, exponent int) Decimal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The created Decimal value. #### Response Example ```go // Example usage: // 12345 * 10^(-4) = 1.2345 d1 := decimal.New(12345, -4) fmt.Println(d1.String()) // Output: 1.2345 // 100 * 10^2 = 10000 d2 := decimal.New(100, 2) fmt.Println(d2.String()) // Output: 10000 ``` ``` -------------------------------- ### Create Decimal from String - NewFromString Source: https://context7.com/shopspring/decimal/llms.txt Parses a string into a Decimal, supporting standard and scientific notation. Handles potential parsing errors. Preserves trailing zeros in the string representation but normalizes them in the output. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // Standard decimal notation d1, err := decimal.NewFromString("-123.45") if err != nil { panic(err) } fmt.Println(d1.String()) // Output: -123.45 // Small decimals d2, err := decimal.NewFromString(".0001") if err != nil { panic(err) } fmt.Println(d2.String()) // Output: 0.0001 // Preserves trailing zeroes in representation d3, err := decimal.NewFromString("1.47000") if err != nil { panic(err) } fmt.Println(d3.String()) // Output: 1.47 // Scientific notation d4, err := decimal.NewFromString("1.5e3") if err != nil { panic(err) } fmt.Println(d4.String()) // Output: 1500 } ``` -------------------------------- ### Perform Division and Division with Rounding Source: https://context7.com/shopspring/decimal/llms.txt Div uses a global precision setting, while DivRound allows explicit precision control. Global precision can be adjusted via DivisionPrecision. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.NewFromInt(10) b := decimal.NewFromInt(3) // Standard division with default precision (16 digits) result := a.Div(b) fmt.Println(result.String()) // Output: 3.3333333333333333 // Division with explicit precision result2 := a.DivRound(b, 4) fmt.Println(result2.String()) // Output: 3.3333 // Change global division precision decimal.DivisionPrecision = 8 result3 := a.Div(b) fmt.Println(result3.String()) // Output: 3.33333333 // Financial calculation: split amount 3 ways amount := decimal.RequireFromString("100.00") share := amount.DivRound(decimal.NewFromInt(3), 2) fmt.Println(share.String()) // Output: 33.33 } ``` -------------------------------- ### Convert Decimal to String Source: https://context7.com/shopspring/decimal/llms.txt String methods provide flexible ways to represent decimals as strings. Use String for standard representation, StringFixed for a specific number of decimal places, and StringFixedBank for banker's rounding. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { d := decimal.RequireFromString("5.456") // Standard string (trims trailing zeros by default) fmt.Println(d.String()) // Output: 5.456 // Fixed decimal places fmt.Println(d.StringFixed(2)) // Output: 5.46 fmt.Println(d.StringFixed(5)) // Output: 5.45600 // Fixed with banker's rounding d2 := decimal.RequireFromString("5.445") fmt.Println(d2.StringFixed(2)) // Output: 5.45 fmt.Println(d2.StringFixedBank(2)) // Output: 5.44 // Zero values zero := decimal.NewFromInt(0) fmt.Println(zero.StringFixed(2)) // Output: 0.00 } ``` -------------------------------- ### Big Integer and Big Rational Conversion Source: https://context7.com/shopspring/decimal/llms.txt Creates Decimals from Go's arbitrary-precision types (big.Int and big.Rat). ```APIDOC ## NewFromBigInt / NewFromBigRat ### Description Creates Decimals from Go's arbitrary-precision types. NewFromBigRat divides numerator by denominator and rounds to the specified precision. ### Method `NewFromBigInt(big.Int, exponent int) Decimal` `NewFromBigRat(big.Rat, precision int) Decimal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The created Decimal value. #### Response Example None ### Error Handling None explicitly mentioned for these methods. ``` -------------------------------- ### Check Decimal Sign Source: https://context7.com/shopspring/decimal/llms.txt Use Sign, IsPositive, IsNegative, and IsZero methods to determine the sign of a decimal value. These methods return -1, 0, or 1 for Sign, and booleans for the others. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { pos := decimal.RequireFromString("10.5") neg := decimal.RequireFromString("-10.5") zero := decimal.NewFromInt(0) // Sign returns -1, 0, or 1 fmt.Println(pos.Sign()) // Output: 1 fmt.Println(neg.Sign()) // Output: -1 fmt.Println(zero.Sign()) // Output: 0 // Boolean checks fmt.Println(pos.IsPositive()) // Output: true fmt.Println(neg.IsNegative()) // Output: true fmt.Println(zero.IsZero()) // Output: true } ``` -------------------------------- ### Access Internal Decimal Representation Source: https://context7.com/shopspring/decimal/llms.txt Exponent, Coefficient, and CoefficientInt64 methods expose the internal components of a decimal number, representing it as coefficient * 10^exponent. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { d := decimal.RequireFromString("123.45") fmt.Println("Exponent:", d.Exponent()) // Output: -2 fmt.Println("Coefficient:", d.Coefficient()) // Output: 12345 fmt.Println("CoefficientInt64:", d.CoefficientInt64()) // Output: 12345 // Verify: 12345 * 10^(-2) = 123.45 } ``` -------------------------------- ### Aggregate Decimal Operations: Min, Max, Sum, Avg Source: https://context7.com/shopspring/decimal/llms.txt Package-level functions Min, Max, Sum, and Avg perform aggregate operations on slices of decimal values, simplifying common calculations. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.RequireFromString("10.5") b := decimal.RequireFromString("20.0") c := decimal.RequireFromString("15.5") // Find minimum and maximum fmt.Println(decimal.Min(a, b, c).String()) // Output: 10.5 fmt.Println(decimal.Max(a, b, c).String()) // Output: 20 // Sum all values sum := decimal.Sum(a, b, c) fmt.Println(sum.String()) // Output: 46 // Calculate average avg := decimal.Avg(a, b, c) fmt.Println(avg.String()) // Output: 15.3333333333333333 } ``` -------------------------------- ### Floor, Ceil, and Truncate Operations Source: https://context7.com/shopspring/decimal/llms.txt Provides Floor (largest integer <= d), Ceil (smallest integer >= d), and Truncate (removes digits without rounding) methods. Truncate can be used to specify precision. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { pos := decimal.RequireFromString("3.7") neg := decimal.RequireFromString("-3.7") // Floor fmt.Println(pos.Floor().String()) // Output: 3 fmt.Println(neg.Floor().String()) // Output: -4 // Ceil fmt.Println(pos.Ceil().String()) // Output: 4 fmt.Println(neg.Ceil().String()) // Output: -3 // Truncate to specific precision d := decimal.RequireFromString("123.456789") fmt.Println(d.Truncate(2).String()) // Output: 123.45 fmt.Println(d.Truncate(4).String()) // Output: 123.4567 } ``` -------------------------------- ### Perform Addition and Subtraction Source: https://context7.com/shopspring/decimal/llms.txt Add and Sub methods return new Decimal values without modifying the original operands. Operations maintain full precision. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.RequireFromString("100.50") b := decimal.RequireFromString("25.75") // Addition sum := a.Add(b) fmt.Println(sum.String()) // Output: 126.25 // Subtraction diff := a.Sub(b) fmt.Println(diff.String()) // Output: 74.75 // Chaining operations c := decimal.RequireFromString("10.00") result := a.Add(b).Sub(c) fmt.Println(result.String()) // Output: 116.25 // Original values unchanged fmt.Println(a.String()) // Output: 100.50 } ``` -------------------------------- ### Sign / IsPositive / IsNegative / IsZero Source: https://context7.com/shopspring/decimal/llms.txt Methods to check the sign of a decimal value. The Sign method returns -1, 0, or 1, while IsPositive, IsNegative, and IsZero return boolean values. ```APIDOC ## Sign Checking Methods ### Description Methods to check the sign of a decimal value. ### Methods - `Sign()`: Returns -1, 0, or 1 based on the sign of the decimal. - `IsPositive()`: Returns `true` if the decimal is positive, `false` otherwise. - `IsNegative()`: Returns `true` if the decimal is negative, `false` otherwise. - `IsZero()`: Returns `true` if the decimal is zero, `false` otherwise. ### Example Usage ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { pos := decimal.RequireFromString("10.5") neg := decimal.RequireFromString("-10.5") zero := decimal.NewFromInt(0) fmt.Println(pos.Sign()) // Output: 1 fmt.Println(neg.Sign()) // Output: -1 fmt.Println(zero.Sign()) // Output: 0 fmt.Println(pos.IsPositive()) // Output: true fmt.Println(neg.IsNegative()) // Output: true fmt.Println(zero.IsZero()) // Output: true } ``` ``` -------------------------------- ### Calculate Exponential Functions Source: https://context7.com/shopspring/decimal/llms.txt Computes e^x using Taylor series or the Hull-Abraham algorithm. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { x := decimal.NewFromFloat(1.0) // e^1 with 10 decimal places result, err := x.ExpTaylor(10) if err != nil { panic(err) } fmt.Println(result.String()) // Output: 2.7182818285 // e^2 with high precision x2 := decimal.NewFromFloat(2.0) result2, _ := x2.ExpTaylor(20) fmt.Println(result2.String()) // Output: 7.38905609893065022723 // Using Hull-Abraham algorithm (faster for small precision) result3, _ := decimal.NewFromFloat(2.5).ExpHullAbrham(6) fmt.Println(result3.String()) // Output: 12.1825 } ``` -------------------------------- ### StringFixedCash for Currency Formatting Source: https://context7.com/shopspring/decimal/llms.txt StringFixedCash applies specific rounding rules suitable for cash transactions, often used for prices in regions with distinct rounding conventions. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { d := decimal.RequireFromString("9.97") fmt.Println(d.StringFixedCash(5)) // Output: 9.95 fmt.Println(d.StringFixedCash(10)) // Output: 10 } ``` -------------------------------- ### Utility Functions: Min / Max / Sum / Avg Source: https://context7.com/shopspring/decimal/llms.txt Package-level functions that perform common aggregate operations on multiple decimal values, such as finding the minimum, maximum, sum, or average. ```APIDOC ## Utility Functions (Aggregate Operations) ### Description Package-level functions for common aggregate operations on multiple decimal values. ### Functions - `Min(decimals ...Decimal)`: Returns the minimum value from a list of decimals. - `Max(decimals ...Decimal)`: Returns the maximum value from a list of decimals. - `Sum(decimals ...Decimal)`: Returns the sum of all provided decimal values. - `Avg(decimals ...Decimal)`: Returns the average of all provided decimal values. ### Example Usage ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.RequireFromString("10.5") b := decimal.RequireFromString("20.0") c := decimal.RequireFromString("15.5") fmt.Println(decimal.Min(a, b, c).String()) // Output: 10.5 fmt.Println(decimal.Max(a, b, c).String()) // Output: 20 sum := decimal.Sum(a, b, c) fmt.Println(sum.String()) // Output: 46 avg := decimal.Avg(a, b, c) fmt.Println(avg.String()) // Output: 15.3333333333333333 } ``` ``` -------------------------------- ### Arithmetic Operations: Div and DivRound Source: https://context7.com/shopspring/decimal/llms.txt Performs division. Div uses global DivisionPrecision, while DivRound allows explicit precision and rounding. ```APIDOC ## Div / DivRound ### Description Division uses the global DivisionPrecision (default 16) for the number of decimal places. DivRound allows specifying precision explicitly and uses proper rounding. ### Method `Div(other Decimal) Decimal` `DivRound(other Decimal, precision int) Decimal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The result of the division. #### Response Example None ### Error Handling None explicitly mentioned for these methods. Division by zero might result in an error or panic. ``` -------------------------------- ### Perform Division with Remainder Source: https://context7.com/shopspring/decimal/llms.txt QuoRem returns both the quotient and the remainder, which is useful for precise financial splitting. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { total := decimal.RequireFromString("100.00") divisor := decimal.NewFromInt(3) // Get quotient and remainder with 2 decimal precision quotient, remainder := total.QuoRem(divisor, 2) fmt.Println("Quotient:", quotient.String()) // Output: 33.33 fmt.Println("Remainder:", remainder.String()) // Output: 0.01 // Verify: quotient * divisor + remainder = total reconstructed := quotient.Mul(divisor).Add(remainder) fmt.Println("Reconstructed:", reconstructed.String()) // Output: 100 } ``` -------------------------------- ### Perform Multiplication Source: https://context7.com/shopspring/decimal/llms.txt The Mul method multiplies two Decimals while preserving all significant digits. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { price := decimal.RequireFromString("19.99") quantity := decimal.NewFromInt(3) total := price.Mul(quantity) fmt.Println(total.String()) // Output: 59.97 // Tax calculation taxRate := decimal.RequireFromString("0.08875") tax := total.Mul(taxRate) fmt.Println(tax.String()) // Output: 5.3223375 // Percentage calculation discount := decimal.RequireFromString("0.15") savings := price.Mul(discount) fmt.Println(savings.String()) // Output: 2.9985 } ``` -------------------------------- ### String Conversion: RequireFromString Source: https://context7.com/shopspring/decimal/llms.txt Creates a Decimal from a string. Panics if the string is invalid. Useful for constants and tests. ```APIDOC ## RequireFromString ### Description Creates a Decimal from a string. Panics if the string is invalid. Useful for constants and tests. ### Method `RequireFromString(string) Decimal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The created Decimal value. #### Response Example None ### Error Handling Panics if the input string is not a valid decimal representation. ``` -------------------------------- ### Banker's Rounding (RoundBank) Source: https://context7.com/shopspring/decimal/llms.txt Compares standard rounding with Banker's rounding (round half to even). Use RoundBank to reduce cumulative rounding bias in financial calculations. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // Standard vs Banker's rounding comparison values := []string{"5.45", "5.55", "5.65", "5.75"} for _, v := range values { d := decimal.RequireFromString(v) fmt.Printf("%s -> Round: %s, RoundBank: %s\n", v, d.Round(1).String(), d.RoundBank(1).String()) } // Output: // 5.45 -> Round: 5.5, RoundBank: 5.4 // 5.55 -> Round: 5.6, RoundBank: 5.6 // 5.65 -> Round: 5.7, RoundBank: 5.6 // 5.75 -> Round: 5.8, RoundBank: 5.8 } ``` -------------------------------- ### Calculate Power Operations Source: https://context7.com/shopspring/decimal/llms.txt Computes powers using decimal, int32, or big.Int exponents. Negative exponents use a default precision of 16. ```go package main import ( "fmt" "math/big" "github.com/shopspring/decimal" ) func main() { base := decimal.NewFromFloat(2.5) // Power with decimal exponent result := base.Pow(decimal.NewFromFloat(3.0)) fmt.Println(result.String()) // Output: 15.625 // Power with int32 exponent (faster) result2, _ := decimal.NewFromFloat(4.0).PowInt32(4) fmt.Println(result2.String()) // Output: 256 // Power with big.Int exponent result3, _ := decimal.NewFromFloat(3.0).PowBigInt(big.NewInt(3)) fmt.Println(result3.String()) // Output: 27 // Negative exponent result4, _ := decimal.NewFromFloat(2.0).PowInt32(-3) fmt.Println(result4.String()) // Output: 0.125 // With explicit precision result5, _ := decimal.NewFromFloat(5.0).PowWithPrecision(decimal.NewFromFloat(0.5), 10) fmt.Println(result5.String()) // Output: 2.2360679775 (square root of 5) } ``` -------------------------------- ### Serialize and Deserialize Decimals with JSON Source: https://context7.com/shopspring/decimal/llms.txt Decimals are serialized as strings by default. Set MarshalJSONWithoutQuotes to true to serialize as numbers, though this should be used with caution. ```go package main import ( "encoding/json" "fmt" "github.com/shopspring/decimal" ) type Product struct { Name string `json:"name"` Price decimal.Decimal `json:"price"` } func main() { // Serialization product := Product{ Name: "Widget", Price: decimal.RequireFromString("19.99"), } jsonBytes, _ := json.Marshal(product) fmt.Println(string(jsonBytes)) // Output: {"name":"Widget","price":"19.99"} // Deserialization jsonStr := `{"name":"Gadget","price":"29.99"}` var p2 Product json.Unmarshal([]byte(jsonStr), &p2) fmt.Println(p2.Price.String()) // Output: 29.99 // Serialize as number (use with caution) decimal.MarshalJSONWithoutQuotes = true jsonBytes2, _ := json.Marshal(product) fmt.Println(string(jsonBytes2)) // Output: {"name":"Widget","price":19.99} } ``` -------------------------------- ### Creating Decimals - NewFromString Source: https://context7.com/shopspring/decimal/llms.txt Parses a string representation of a decimal number, supporting standard and scientific notation. Returns an error if the string cannot be parsed. ```APIDOC ## Creating Decimals - NewFromString ### Description Parses a string representation of a decimal number, supporting standard decimal notation and scientific notation. This is the recommended way to create Decimals for precise values. Returns an error if the string cannot be parsed. ### Method `NewFromString(s string) (Decimal, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The parsed Decimal value. - **error** (error) - An error if parsing fails. #### Response Example ```go // Example usage: d1, err := decimal.NewFromString("-123.45") if err != nil { panic(err) } fmt.Println(d1.String()) // Output: -123.45 ``` ``` -------------------------------- ### Value Extraction: IntPart / BigInt / Float64 / InexactFloat64 Source: https://context7.com/shopspring/decimal/llms.txt Methods to extract the decimal value into various standard Go numeric types, including integer parts and floating-point representations with exactness indicators. ```APIDOC ## Value Extraction Methods (Numeric Types) ### Description Methods to extract the decimal value in various Go numeric types. ### Methods - `IntPart()`: Returns the integer part of the decimal. - `BigInt()`: Returns the integer part as a `*big.Int`. - `Float64()`: Returns the decimal as a `float64` and a boolean indicating if the conversion was exact. - `InexactFloat64()`: Returns the decimal as a `float64` without checking for exactness. ### Example Usage ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { d := decimal.RequireFromString("123.456") fmt.Println(d.IntPart()) // Output: 123 bigInt := d.BigInt() fmt.Println(bigInt.String()) // Output: 123 f, exact := d.Float64() fmt.Printf("%.6f, exact: %v\n", f, exact) // Output: 123.456000, exact: true f2 := d.InexactFloat64() fmt.Printf("%.6f\n", f2) // Output: 123.456000 } ``` ``` -------------------------------- ### String Conversion: String / StringFixed / StringFixedBank Source: https://context7.com/shopspring/decimal/llms.txt Methods for converting decimal values to strings. String provides the standard representation, StringFixed formats to a specific number of decimal places, and StringFixedBank uses banker's rounding. ```APIDOC ## String Conversion Methods ### Description Methods for converting decimal values to strings with different formatting options. ### Methods - `String()`: Returns the decimal representation, trimming trailing zeros by default. - `StringFixed(prec int)`: Returns a string with exactly `prec` decimal places, using standard rounding. - `StringFixedBank(prec int)`: Returns a string with exactly `prec` decimal places, using banker's rounding. ### Example Usage ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { d := decimal.RequireFromString("5.456") fmt.Println(d.String()) // Output: 5.456 fmt.Println(d.StringFixed(2)) // Output: 5.46 fmt.Println(d.StringFixed(5)) // Output: 5.45600 d2 := decimal.RequireFromString("5.445") fmt.Println(d2.StringFixedBank(2)) // Output: 5.44 zero := decimal.NewFromInt(0) fmt.Println(zero.StringFixed(2)) // Output: 0.00 } ``` ``` -------------------------------- ### Extract Decimal Value as Go Numeric Types Source: https://context7.com/shopspring/decimal/llms.txt Methods like IntPart, BigInt, Float64, and InexactFloat64 allow extraction of the decimal's value into standard Go integer and floating-point types. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { d := decimal.RequireFromString("123.456") // Integer part only fmt.Println(d.IntPart()) // Output: 123 // As big.Int (integer part) bigInt := d.BigInt() fmt.Println(bigInt.String()) // Output: 123 // As float64 with exactness indicator f, exact := d.Float64() fmt.Printf("%.6f, exact: %v\n", f, exact) // Output: 123.456000, exact: true // As float64 without exactness check f2 := d.InexactFloat64() fmt.Printf("%.6f\n", f2) // Output: 123.456000 } ``` -------------------------------- ### Creating Decimals - NewFromFloat / NewFromFloat32 Source: https://context7.com/shopspring/decimal/llms.txt Converts floating-point values to Decimal, preserving the number of significant digits that can be reliably represented in the original float type. Use with caution as floats may already have precision errors. ```APIDOC ## Creating Decimals - NewFromFloat / NewFromFloat32 ### Description Converts floating-point values to Decimal, preserving the number of significant digits that can be reliably represented in the original float type. Use with caution as floats may already have precision errors. ### Method - `NewFromFloat(f float64) Decimal` - `NewFromFloat32(f float32) Decimal` - `NewFromFloatWithExponent(f float64, exponent int) Decimal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Decimal** (decimal.Decimal) - The created Decimal value. #### Response Example ```go // Example usage: d1 := decimal.NewFromFloat(123.456) fmt.Println(d1.String()) // Output: 123.456 d3 := decimal.NewFromFloat32(3.14159) fmt.Println(d3.String()) // Output: 3.14159 d4 := decimal.NewFromFloatWithExponent(123.456, -2) fmt.Println(d4.String()) // Output: 123.46 ``` ``` -------------------------------- ### Calculate Natural Logarithm Source: https://context7.com/shopspring/decimal/llms.txt Computes the natural logarithm. Returns an error for non-positive input values. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // ln(e) = 1 e := decimal.RequireFromString("2.718281828459045") result, err := e.Ln(10) if err != nil { panic(err) } fmt.Println(result.String()) // Output: 1 // ln(10) ten := decimal.NewFromFloat(10.0) result2, _ := ten.Ln(15) fmt.Println(result2.String()) // Output: 2.302585092994046 // ln(100) with 5 decimal places hundred := decimal.NewFromFloat(100.0) result3, _ := hundred.Ln(5) fmt.Println(result3.String()) // Output: 4.60517 } ``` -------------------------------- ### Perform Modulo Operation Source: https://context7.com/shopspring/decimal/llms.txt Calculates the remainder of division. The result retains the sign of the dividend. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { a := decimal.RequireFromString("10.5") b := decimal.RequireFromString("3") remainder := a.Mod(b) fmt.Println(remainder.String()) // Output: 1.5 // Negative dividend c := decimal.RequireFromString("-10.5") remainder2 := c.Mod(b) fmt.Println(remainder2.String()) // Output: -1.5 } ``` -------------------------------- ### Perform Trigonometric Calculations Source: https://context7.com/shopspring/decimal/llms.txt Trigonometric functions like Sin, Cos, Tan, and Atan operate on decimal values representing radians. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { // Pi/4 radians = 45 degrees pi4 := decimal.RequireFromString("0.7853981633974483") sin := pi4.Sin() cos := pi4.Cos() tan := pi4.Tan() fmt.Printf("sin(π/4) = %s\n", sin.Round(10).String()) // Output: sin(π/4) = 0.7071067812 fmt.Printf("cos(π/4) = %s\n", cos.Round(10).String()) // Output: cos(π/4) = 0.7071067812 fmt.Printf("tan(π/4) = %s\n", tan.Round(10).String()) // Output: tan(π/4) = 1 // Arctangent one := decimal.NewFromFloat(1.0) atan := one.Atan() fmt.Printf("atan(1) = %s\n", atan.Round(10).String()) // Output: atan(1) = 0.7853981634 (π/4) } ``` -------------------------------- ### Negate and Absolute Value Source: https://context7.com/shopspring/decimal/llms.txt Computes the negation or absolute value of a decimal number. ```go package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { positive := decimal.RequireFromString("123.45") negative := decimal.RequireFromString("-123.45") // Negation fmt.Println(positive.Neg().String()) // Output: -123.45 fmt.Println(negative.Neg().String()) // Output: 123.45 // Absolute value fmt.Println(positive.Abs().String()) // Output: 123.45 fmt.Println(negative.Abs().String()) // Output: 123.45 } ``` -------------------------------- ### Natural Logarithm Source: https://context7.com/shopspring/decimal/llms.txt API for calculating the natural logarithm (ln) of a decimal number with specified precision. ```APIDOC ## Ln ### Description Calculates the natural logarithm. Returns an error for non-positive values since ln(x) is undefined for x <= 0. ### Method `Ln` ### Parameters - `precision` (uint32): The desired precision for the result. ### Request Example ```go // ln(e) = 1 e := decimal.RequireFromString("2.718281828459045") result, err := e.Ln(10) if err != nil { panic(err) } fmt.Println(result.String()) // ln(10) ten := decimal.NewFromFloat(10.0) result2, _ := ten.Ln(15) fmt.Println(result2.String()) // ln(100) with 5 decimal places hundred := decimal.NewFromFloat(100.0) result3, _ := hundred.Ln(5) fmt.Println(result3.String()) ``` ### Response #### Success Response (decimal.Decimal) - The natural logarithm of the input decimal number, with the specified precision. #### Response Example ``` 1 2.302585092994046 4.60517 ``` ```