mathx

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2025 License: Apache-2.0 Imports: 6 Imported by: 0

README

MathX - High Precision Decimal Math Library

A high-precision decimal math library for Go that provides accurate floating-point arithmetic operations using the shopspring/decimal library under the hood. MathX offers a clean, chainable API for mathematical operations with precise decimal calculations.

Features

  • High Precision: Uses shopspring/decimal for accurate decimal arithmetic
  • Chainable API: Fluent interface for mathematical operations
  • Type Safety: Compile-time type checking with generic support
  • Comprehensive: Basic operations, statistical functions, formatting utilities
  • Zero Dependencies: Only depends on shopspring/decimal and standard library

Installation

go get github.com/go4x/goal/mathx

Quick Start

package main

import (
    "fmt"
    "github.com/go4x/goal/mathx"
)

func main() {
    // Basic arithmetic with precision
    result := mathx.Add(0.1, 0.2)
    fmt.Println(result) // 0.3 (not 0.30000000000000004)
    
    // Chainable operations
    formatted := mathx.Add(0.1, 0.2).
        Mul(10).
        Div(3, 2).
        Round(2).
        ToString()
    fmt.Println(formatted) // "1.00"
    
    // Money formatting
    price := mathx.Mul(99.99, 1.15).
        Round(2).
        FormatMoney(2)
    fmt.Printf("Price: $%s\n", price) // Price: $114.99
}

Core Concepts

Result Type

All mathematical operations return a Result type that can be used in two ways:

  1. Direct usage: Returns float64 when used directly
  2. Chainable methods: Call methods for formatting and further operations
// Direct usage
sum := mathx.Add(1, 2) // Returns Result, but can be used as float64
fmt.Println(sum) // 3

// Chainable usage
str := mathx.Add(1, 2).ToString() // "3"

API Reference

Basic Arithmetic
Add
func Add(a, b float64) Result

Adds two numbers with decimal precision.

result := mathx.Add(0.1, 0.2) // 0.3
Sub
func Sub(a, b float64) Result

Subtracts two numbers with decimal precision.

result := mathx.Sub(5.0, 2.0) // 3.0
Mul
func Mul(a, b float64) Result

Multiplies two numbers with decimal precision.

result := mathx.Mul(3.0, 4.0) // 12.0
Div
func Div(a, b float64, precision int32) Result

Divides two numbers with specified precision.

result := mathx.Div(10.0, 3.0, 2) // 3.33
DivTrunc
func DivTrunc(a, b float64, precision int32) Result

Divides two numbers and truncates to specified precision.

result := mathx.DivTrunc(10.0, 3.0, 2) // 3.33
Mathematical Functions
Round
func Round(value float64, precision int32) Result

Rounds a number to specified decimal places.

result := mathx.Round(3.145, 2) // 3.15
Truncate
func Truncate(value float64, precision int32) Result

Truncates a number to specified decimal places.

result := mathx.Truncate(3.145, 2) // 3.14
Abs
func Abs(value float64) float64

Returns the absolute value of a number.

result := mathx.Abs(-3.14) // 3.14
Ceil
func Ceil(value float64) float64

Returns the smallest integer greater than or equal to the value.

result := mathx.Ceil(3.2) // 4.0
Floor
func Floor(value float64) float64

Returns the largest integer less than or equal to the value.

result := mathx.Floor(3.8) // 3.0
Pow
func Pow(base, exponent float64) float64

Raises a number to the power of another.

result := mathx.Pow(2.0, 3.0) // 8.0
Sqrt
func Sqrt(value float64) float64

Returns the square root of a number.

result := mathx.Sqrt(16.0) // 4.0
Statistical Functions
Average
func Average[T constraints.Integer | constraints.Float](ns ...T) float64

Calculates the average of a slice of numbers.

avg := mathx.Average(1, 2, 3, 4, 5) // 3.0
Median
func Median[T constraints.Integer | constraints.Float](ns ...T) float64

Calculates the median of a slice of numbers.

median := mathx.Median(1, 2, 3, 4, 5) // 3.0
StandardDeviation
func StandardDeviation[T constraints.Integer | constraints.Float](ns ...T) float64

Calculates the standard deviation of a slice of numbers.

std := mathx.StandardDeviation(1, 2, 3, 4, 5) // 1.4142135623730951
Max
func Max[T constraints.Ordered](ns ...T) T

Returns the maximum value from a slice of numbers.

max := mathx.Max(1, 5, 3, 9, 2) // 9.0
Min
func Min[T constraints.Ordered](ns ...T) T

Returns the minimum value from a slice of numbers.

min := mathx.Min(1, 5, 3, 9, 2) // 1.0
Sum
func Sum[T constraints.Integer | constraints.Float](ns ...T) T

Returns the sum of a slice of numbers.

sum := mathx.Sum(1, 2, 3, 4, 5) // 15.0
Utility Functions
Clamp
func Clamp(value, min, max float64) float64

Clamps a value between min and max.

result := mathx.Clamp(15.0, 0.0, 10.0) // 10.0
Lerp
func Lerp(a, b, t float64) float64

Performs linear interpolation between two values.

result := mathx.Lerp(0.0, 10.0, 0.5) // 5.0
Percentage
func Percentage(value, percent float64) float64

Calculates percentage of a value.

result := mathx.Percentage(100.0, 15.0) // 15.0
CompoundInterest
func CompoundInterest(principal, rate float64, periods int) float64

Calculates compound interest.

result := mathx.CompoundInterest(1000.0, 0.1, 2) // 1210.0
SafeDiv
func SafeDiv(dividend, divisor float64, precision int32) float64

Safely divides two numbers, returns 0 if divisor is 0.

result := mathx.SafeDiv(10.0, 0.0, 2) // 0.0
String Conversion
ToString
func ToString(value float64) string

Converts a float64 to string.

str := mathx.ToString(3.14) // "3.14"
ToStringFixed
func ToStringFixed(value float64, places int32) string

Converts a float64 to string with fixed decimal places.

str := mathx.ToStringFixed(3.14159, 2) // "3.14"
ToStringBank
func ToStringBank(value float64, places int32) string

Converts a float64 to string with banker's rounding.

str := mathx.ToStringBank(3.145, 2) // "3.14"
FormatMoney
func FormatMoney(amount float64, decimalPlaces int32) string

Formats a number as currency with thousands separator.

str := mathx.FormatMoney(1234567.89, 2) // "1,234,567.89"
ParseFloat
func ParseFloat(s string) (float64, error)

Safely parses a string to float64.

value, err := mathx.ParseFloat("3.14")
if err == nil {
    fmt.Println(value) // 3.14
}
Result Methods

The Result type provides chainable methods for further operations:

String Conversion
result.ToString() string
result.ToStringFixed(places int32) string
result.ToStringBank(places int32) string
Formatting
result.FormatMoney(decimalPlaces int32) string
result.Clean() Result // Removes trailing zeros
Mathematical Operations
result.Add(other float64) Result
result.Sub(other float64) Result
result.Mul(other float64) Result
result.Div(other float64, precision int32) Result
result.Round(places int32) Result
result.Truncate(places int32) Result
result.Abs() Result
result.Neg() Result
Value Extraction
result.Float64() float64
result.String() string

Examples

Financial Calculations
package main

import (
    "fmt"
    "github.com/go4x/goal/mathx"
)

func main() {
    // Calculate tax
    price := 99.99
    taxRate := 0.08
    tax := mathx.Mul(price, taxRate).Round(2)
    
    // Calculate total
    total := mathx.Add(price, tax.Float64())
    
    // Format as currency
    formatted := total.FormatMoney(2)
    fmt.Printf("Total: $%s\n", formatted) // Total: $107.99
}
Statistical Analysis
package main

import (
    "fmt"
    "github.com/go4x/goal/mathx"
)

func main() {
    scores := []float64{85, 92, 78, 96, 88}
    
    avg := mathx.Average(scores...)
    median := mathx.Median(scores...)
    std := mathx.StandardDeviation(scores...)
    
    fmt.Printf("Average: %.2f\n", avg)
    fmt.Printf("Median: %.2f\n", median)
    fmt.Printf("Standard Deviation: %.2f\n", std)
}
Chainable Operations
package main

import (
    "fmt"
    "github.com/go4x/goal/mathx"
)

func main() {
    // Complex calculation with formatting
    result := mathx.Add(0.1, 0.2).
        Mul(100).
        Div(3, 4).
        Round(2).
        Clean().
        ToString()
    
    fmt.Println(result) // "10.00"
}
Percentage Calculations
package main

import (
    "fmt"
    "github.com/go4x/goal/mathx"
)

func main() {
    // Calculate tip
    bill := 50.00
    tipPercent := 18.0
    tip := mathx.Percentage(bill, tipPercent)
    
    // Calculate total
    total := mathx.Add(bill, tip)
    
    fmt.Printf("Bill: $%.2f\n", bill)
    fmt.Printf("Tip (%.0f%%): $%.2f\n", tipPercent, tip)
    fmt.Printf("Total: $%.2f\n", total.Float64())
}

Performance Considerations

  • MathX uses shopspring/decimal internally for high precision
  • String conversions may have slight overhead compared to native float64 operations
  • For performance-critical applications, consider using the direct float64 return values
  • Chainable operations create new Result instances, so use judiciously in tight loops

Error Handling

Most functions return float64 or Result types directly. Functions that can fail (like ParseFloat) return (value, error) tuples.

value, err := mathx.ParseFloat("invalid")
if err != nil {
    // Handle error
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is part of the goal project and follows the same license terms.

Acknowledgments

  • Built on top of the excellent shopspring/decimal library
  • Inspired by the need for precise decimal arithmetic in Go applications

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs(value float64) float64

Abs returns the absolute value of a number

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Mathematical functions
	fmt.Printf("Abs(-3.14): %.2f\n", mathx.Abs(-3.14))
	fmt.Printf("Ceil(3.14): %.0f\n", mathx.Ceil(3.14))
	fmt.Printf("Floor(3.14): %.0f\n", mathx.Floor(3.14))
	fmt.Printf("Pow(2, 3): %.0f\n", mathx.Pow(2, 3))
	fmt.Printf("Sqrt(16): %.0f\n", mathx.Sqrt(16))
}
Output:

Abs(-3.14): 3.14
Ceil(3.14): 4
Floor(3.14): 3
Pow(2, 3): 8
Sqrt(16): 4

func Average

func Average[T constraints.Integer | constraints.Float](ns ...T) float64

Average calculates the average of a slice of numbers

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Statistical calculations
	scores := []float64{85, 92, 78, 96, 88}

	avg := mathx.Average(scores...)
	median := mathx.Median(scores...)
	std := mathx.StandardDeviation(scores...)

	fmt.Printf("Average: %.2f\n", avg)
	fmt.Printf("Median: %.2f\n", median)
	fmt.Printf("Standard Deviation: %.2f\n", std)
}
Output:

Average: 87.80
Median: 88.00
Standard Deviation: 6.87

func BigFloatMul

func BigFloatMul(multiplicand, multiplier *big.Float) *big.Float

BigFloatMul multiplies two big.Float values using decimal precision

func Ceil

func Ceil(value float64) float64

Ceil returns the smallest integer greater than or equal to the value

func Clamp

func Clamp(value, min, max float64) float64

Clamp clamps a value between min and max

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Utility functions
	value := 15.0
	min := 0.0
	max := 10.0

	clamped := mathx.Clamp(value, min, max)
	fmt.Printf("Clamp(%.0f, %.0f, %.0f): %.0f\n", value, min, max, clamped)

	// Linear interpolation
	lerp := mathx.Lerp(0.0, 10.0, 0.5)
	fmt.Printf("Lerp(0, 10, 0.5): %.1f\n", lerp)
}
Output:

Clamp(15, 0, 10): 10
Lerp(0, 10, 0.5): 5.0

func CleanFloat

func CleanFloat(value float64) float64

CleanFloat removes trailing zeros and returns a clean float64

func CleanFloatString

func CleanFloatString(value float64) string

CleanFloatString removes trailing zeros and returns a clean string representation

func CompoundInterest

func CompoundInterest(principal, rate float64, periods int) float64

CompoundInterest calculates compound interest

func DecimalMax

func DecimalMax(ds ...decimal.Decimal) decimal.Decimal

DecimalMax returns the maximum decimal value

func DecimalMin

func DecimalMin(ds ...decimal.Decimal) decimal.Decimal

DecimalMin returns the minimum decimal value

func DecimalSum

func DecimalSum(ds ...decimal.Decimal) decimal.Decimal

DecimalSum returns the sum of decimal values

func Floor

func Floor(value float64) float64

Floor returns the largest integer less than or equal to the value

func FormatCurrency

func FormatCurrency(amount float64, decimalPlaces int32) string

FormatCurrency formats a number as currency with specified decimal places

func FormatMoney

func FormatMoney(amount float64, decimalPlaces int32) string

FormatMoney formats a number as currency with thousands separator

func FormatMoneyInt

func FormatMoneyInt(amount int64, decimalPlaces int32) string

FormatMoneyInt formats an int64 as currency with thousands separator

func Int64Div

func Int64Div(dividend, divisor int64, precision int32) float64

Int64Div divides two int64 values with specified precision

func Int64DivTrunc

func Int64DivTrunc(dividend, divisor int64, precision int32) float64

Int64DivTrunc truncates the division of two int64 values

func Int64MulFloat64

func Int64MulFloat64(multiplicand int64, multiplier float64) float64

Int64MulFloat64 multiplies int64 and float64 using decimal precision

func IsEqual

func IsEqual(a, b float64) bool

IsEqual checks if two numbers are equal (within a small epsilon)

func IsNegative

func IsNegative(value float64) bool

IsNegative checks if a number is negative

func IsPositive

func IsPositive(value float64) bool

IsPositive checks if a number is positive

func IsZero

func IsZero(value float64) bool

IsZero checks if a number is zero (within a small epsilon)

func Lerp

func Lerp(a, b, t float64) float64

Lerp performs linear interpolation between two values

func Max

func Max[T constraints.Ordered](ns ...T) T

Max returns the maximum value from a slice of numbers

func Median

func Median[T constraints.Integer | constraints.Float](ns ...T) float64

Median calculates the median of a slice of numbers

func Min

func Min[T constraints.Ordered](ns ...T) T

Min returns the minimum value from a slice of numbers

func ParseFloat

func ParseFloat(s string) (float64, error)

ParseFloat safely parses a string to float64

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Safe string parsing
	value, err := mathx.ParseFloat("3.14")
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Printf("Parsed value: %.2f\n", value)
}
Output:

Parsed value: 3.14

func Percentage

func Percentage(value, percent float64) float64

Percentage calculates percentage of a value

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Calculate tip
	bill := 50.00
	tipPercent := 18.0
	tip := mathx.Percentage(bill, tipPercent)

	// Calculate total
	total := mathx.Add(bill, tip)

	fmt.Printf("Bill: $%.2f\n", bill)
	fmt.Printf("Tip (%.0f%%): $%.2f\n", tipPercent, tip)
	fmt.Printf("Total: $%.2f\n", total.Float64())
}
Output:

Bill: $50.00
Tip (18%): $9.00
Total: $59.00

func Pow

func Pow(base, exponent float64) float64

Pow raises a number to the power of another

func RemoveTrailingZeros

func RemoveTrailingZeros(value float64) string

RemoveTrailingZeros removes trailing zeros from a float64 string representation

func RemoveTrailingZerosFixed

func RemoveTrailingZerosFixed(value float64, places int32) string

RemoveTrailingZerosFixed removes trailing zeros from a float64 with fixed decimal places

func SafeDiv

func SafeDiv(dividend, divisor float64, precision int32) float64

SafeDiv safely divides two numbers, returns 0 if divisor is 0

func Sign

func Sign(value float64) int

Sign returns the sign of a number (-1, 0, or 1)

func Sqrt

func Sqrt(value float64) float64

Sqrt returns the square root of a number

func StandardDeviation

func StandardDeviation[T constraints.Integer | constraints.Float](ns ...T) float64

StandardDeviation calculates the standard deviation of a slice of numbers

func Sum

func Sum[T constraints.Integer | constraints.Float](ns ...T) T

Sum returns the sum of a slice of numbers

func ToFixed

func ToFixed(value float64, places int32) float64

ToFixed formats a number to a fixed number of decimal places

func ToString

func ToString(value float64) string

ToString converts a float64 to string

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Various string conversion methods
	value := 3.14159

	fmt.Printf("ToString: %s\n", mathx.ToString(value))
	fmt.Printf("ToStringFixed(2): %s\n", mathx.ToStringFixed(value, 2))
	fmt.Printf("ToStringBank(2): %s\n", mathx.ToStringBank(value, 2))
}
Output:

ToString: 3.14159
ToStringFixed(2): 3.14
ToStringBank(2): 3.14

func ToStringBank

func ToStringBank(value float64, places int32) string

ToStringBank converts a float64 to string with banker's rounding

func ToStringFixed

func ToStringFixed(value float64, places int32) string

ToStringFixed converts a float64 to string with fixed decimal places

Types

type Result

type Result struct {
	// contains filtered or unexported fields
}

Result represents a calculation result with chainable methods

func Add

func Add(a, b float64) Result

Add adds two float64 values using decimal precision and returns a Result

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Basic addition with precision
	result := mathx.Add(0.1, 0.2)
	fmt.Printf("0.1 + 0.2 = %.10f\n", result.Float64())
}
Output:

0.1 + 0.2 = 0.3000000000
Example (Chainable)
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Chainable operations
	result := mathx.Add(0.1, 0.2).
		Mul(10).
		Div(3, 2).
		Round(2).
		ToStringFixed(2)
	fmt.Printf("Result: %s\n", result)
}
Output:

Result: 1.00
Example (Clean)
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Remove trailing zeros
	result := mathx.Add(0.1, 0.2).
		Clean().
		ToString()
	fmt.Printf("Clean result: %s\n", result)
}
Output:

Clean result: 0.3

func Div

func Div(a, b float64, precision int32) Result

Div divides two float64 values using decimal precision and returns a Result

func DivTrunc

func DivTrunc(a, b float64, precision int32) Result

DivTrunc truncates the division of two float64 values and returns a Result

func Mul

func Mul(a, b float64) Result

Mul multiplies two float64 values using decimal precision and returns a Result

Example
package main

import (
	"fmt"

	"github.com/go4x/goal/mathx"
)

func main() {
	// Money formatting with thousands separator
	price := mathx.Mul(99.99, 1.15).
		Round(2).
		FormatMoney(2)
	fmt.Printf("Price: $%s\n", price)
}
Output:

Price: $114.99

func NewResult

func NewResult(value float64) Result

NewResult creates a new Result from a float64

func Round

func Round(value float64, precision int32) Result

Round rounds a float64 to specified precision and returns a Result

func Sub

func Sub(a, b float64) Result

Sub subtracts two float64 values using decimal precision and returns a Result

func Truncate

func Truncate(value float64, precision int32) Result

Truncate truncates a float64 to specified precision and returns a Result

func (Result) Abs

func (r Result) Abs() Result

Abs returns the absolute value

func (Result) Add

func (r Result) Add(other float64) Result

Add adds another value to this result

func (Result) Clean

func (r Result) Clean() Result

Clean removes trailing zeros and returns a new Result

func (Result) Div

func (r Result) Div(other float64, precision int32) Result

Div divides this result by another value

func (Result) DivTrunc

func (r Result) DivTrunc(other float64, precision int32) Result

DivTrunc truncates the division

func (Result) Float64

func (r Result) Float64() float64

Float64 returns the float64 value

func (Result) FormatMoney

func (r Result) FormatMoney(decimalPlaces int32) string

FormatMoney formats as currency with thousands separator

func (Result) Mul

func (r Result) Mul(other float64) Result

Mul multiplies this result by another value

func (Result) Neg

func (r Result) Neg() Result

Neg returns the negative value

func (Result) Round

func (r Result) Round(places int32) Result

Round rounds to specified precision and returns a new Result

func (Result) String

func (r Result) String() string

String returns the string representation

func (Result) Sub

func (r Result) Sub(other float64) Result

Sub subtracts another value from this result

func (Result) ToString

func (r Result) ToString() string

ToString returns the string representation

func (Result) ToStringBank

func (r Result) ToStringBank(places int32) string

ToStringBank returns the string with banker's rounding

func (Result) ToStringFixed

func (r Result) ToStringFixed(places int32) string

ToStringFixed returns the string with fixed decimal places

func (Result) Truncate

func (r Result) Truncate(places int32) Result

Truncate truncates to specified precision and returns a new Result

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL