decimal

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 11 Imported by: 0

README

decimal-go logo An arbitrary-precision decimal arithmetic library for Go.

Go License decimal.js Dependencies

Tests Race detector Cross-validated Performance

A Go implementation inspired by the behavior and API of decimal.js.


About

decimal-go is a Go implementation inspired by the behavior and API of decimal.js, created during the Port Mortem 2026 hackathon.

Goals

  • Preserve the behavior of the original library as closely as possible.
  • Provide an idiomatic Go API.
  • Maintain high test compatibility.
  • Produce clean, well-documented Go code.

Installation

decimal-go has zero external dependencies and requires Go 1.25+.

go get github.com/iSundram/decimal-go

Then import it in your code:

import "github.com/iSundram/decimal-go"

Values are arbitrary-precision and immutable; every operation returns a new value. The package-level New uses the default constructor (precision 20, half-up rounding).

Quick Start

package main

import (
	"fmt"

	"github.com/iSundram/decimal-go"
)

func main() {
	// Money math that never flaunts float rounding.
	price := decimal.New("19.99")
	qty := decimal.New("3")
	total := price.Times(qty)
	fmt.Println(total) // 59.97

	// Exact value parsing from strings, integers, floats or *big.Int.
	fmt.Println(decimal.New("0.1").Plus(decimal.New("0.2"))) // 0.3

	// Custom precision via a cloned constructor.
	c := decimal.Default.Clone(&decimal.Config{Precision: decimal.I64(50)})
	pi := c.New("3.14159265358979323846264338327950288419716939937510")
	fmt.Println(pi.ToFixed(30))
}

Output:

59.97
0.3
3.141592653589793238462643383280

See the example tests, the operations matrix, the decimal.js migration guide and the changelog for more.

Status

Test suite fully ported.

The complete decimal.js test suite is ported to Go: all 62 test modules are covered by white-box tests in package decimal, and go test ./... is green.

  • Run the suite: go test -count=1 ./...
  • Run with the race detector: go test -race -count=1 .
  • Porting rules live in PORTING_TESTS.md.

Validation added in this fork

Beyond the ported suites, exact parity with the live decimal.js is proven by additional committed tests and tooling:

  • Cross-validation (xvalidate/): a shared corpus of values is run through both decimal-go (go run) and the real decimal.js (node); the two outputs are byte-for-byte identical (bash xvalidate/compare.sh, 1518/1518 lines).
  • API parity (parity.go): the 42 decimal.js long method names and toJSON/MarshalJSON exist as aliases and are equal-checked against the primary methods — mirroring the real methods in decimal.js.
  • Property-based tests (property_test.go): round-trip, commutativity, add/sub & mul/div inverses, sqrt/cbrt/exp-log inverses, comparisons, exact sqrt, modulo range.
  • Stress + race tests (stress_test.go): precision 400–2048, integer boundaries, NaN/Infinity, and 64 concurrent clone-constructors under -race. A genuine data race inherited from decimal.js's module globals (external/inexact/quadrant) was found and fixed by moving those flags onto the Constructor (matching decimal.js's "one clone per context" model).
  • Regression tests (regression_test.go): the three bugs fixed while porting (pow10 overflow, Pow negative-base index, 1^±Inf) are locked in.
  • Input matrix (input_test.go): every decimal.js value type (number, string, big.Int, Decimal, -0, NaN, ±Infinity) accepted.
  • Operations matrix (MATRIX.md) documents every op, its rounding semantics and edge cases.
  • Benchmarks (bench/README.md + results.txt): honest Go-vs-JS comparison (18 of 20 comparable ops faster in Go, up to ~3× on multiplication/division); New(string) parsing is ~1.45× slower and parse+format round trips ~1.7× slower, as real-world work re-parses inputs.

Contributing

We welcome contributions! Please see our Contributing Guide for details on how to get started.

Acknowledgements

MikeMcl
Michael Mclaughlin
Huge thanks to Michael Mclaughlin for the original decimal.js library, which heavily inspired the API, design, and behavior of this project.

Contributors

Thanks goes to these wonderful people who have contributed to this project. This section automatically updates as new developers join in!

Contributors

License

This project is released under the MIT License.


Made with Go.

Documentation

Overview

Package decimal provides an arbitrary-precision decimal floating-point type for Go.

It is a port of the decimal.js library (v10.6.0) and preserves its behavior — rounding modes, error conditions and string formatting rules — while exposing an idiomatic Go API. Behavioral parity with the original library is verified byte-for-byte by the cross-validation harness in xvalidate/ and by the ported test suite.

Representation

The value of a Decimal is:

sign * coefficient * 10^exponent

where the coefficient is stored as a slice of base 1e7 words. A nil digits slice represents Infinity (sign != 0) or NaN (sign == 0). All Decimal values are immutable: every operation returns a new value and never mutates its operands.

Constructing values

The package-level New function and the Default constructor parse strings, integers, floats, *big.Int values and other Decimals:

x := decimal.New("123.456")           // from string
y := decimal.New(42)                   // from integer
z := x.Plus(y)                         // 165.456

Invalid values cause a panic with a message prefixed by "[DecimalError]", mirroring decimal.js error semantics.

Configuration

The Default constructor applies the decimal.js defaults (precision 20, half-up rounding, toExpNeg -7, toExpPos 21). A cloned constructor with different settings is created with Constructor.Clone, or an existing one can be reconfigured with Constructor.Config:

c := decimal.Default.Clone(&decimal.Config{Precision: decimal.I64(50)})
pi := c.New("3.14159...") // rounded to 50 significant digits

The rounding modes are exposed as rounding-mode constants (RoundUp, RoundDown, RoundCeil, RoundFloor, RoundHalfUp, RoundHalfDown, RoundHalfEven, RoundHalfCeil, RoundHalfFloor); Euclid selects Euclidean division in the modulo operation.

Concurrency

A Decimal instance is safe for concurrent read-only use. Constructors carry mutable state (rounding results, intermediate flags), so follow the decimal.js guidance: give each concurrent context its own cloned constructor. A single *Constructor shared without synchronisation is not supported.

API compatibility

Methods follow idiomatic Go name() names (Plus, Minus, Times, Div, Pow, Sqrt, Sin, ...). The decimal.js long-form names (DividedBy, NaturalLogarithm, SquareRoot, ...), ToJSON and MarshalJSON are provided as aliases in parity.go. String returns the decimal.js toString() form; ValueOf returns the valueOf() form (which, unlike String, keeps the leading minus sign of -0).

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

func main() {
	// Money calculation without float rounding surprises.
	c := dec.Default.Clone(&dec.Config{
		Precision: dec.I64(12),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-100),
		ToExpPos:  dec.I64(100),
	})
	price := c.New("19.99")
	total := price.Times(c.New("3"))
	fmt.Println(total)
}
Output:
59.97

Index

Examples

Constants

View Source
const (
	RoundUp        = 0 // Away from zero.
	RoundDown      = 1 // Towards zero.
	RoundCeil      = 2 // Towards +Infinity.
	RoundFloor     = 3 // Towards -Infinity.
	RoundHalfUp    = 4 // Nearest; ties up.
	RoundHalfDown  = 5 // Nearest; ties down.
	RoundHalfEven  = 6 // Nearest; ties to even.
	RoundHalfCeil  = 7 // Nearest; ties ceil.
	RoundHalfFloor = 8 // Nearest; ties floor.

	// Euclid is a modulo mode (not a rounding mode): Euclidean division.
	// q = sign(y) * floor(x / abs(y)); the remainder is always non-negative.
	Euclid = 9
)

Rounding modes.

Variables

View Source
var Default = defaultConstructor()

Default is the package-level default Decimal constructor, mirroring the default Decimal export of decimal.js.

Functions

func Bool

func Bool(v bool) *bool

Bool is a helper for building Config pointer fields.

func I64

func I64(v int64) *int64

I64 is a helper for building Config pointer fields.

func IsDecimal

func IsDecimal(v any) bool

IsDecimal returns true if v is a *Decimal.

Types

type Config

type Config struct {
	Precision *int64
	Rounding  *int64
	Modulo    *int64
	ToExpNeg  *int64
	ToExpPos  *int64
	MinE      *int64
	MaxE      *int64
	Crypto    *bool
	Defaults  bool
}

Config is the options struct accepted by Constructor.Config and Constructor.Clone. Nil pointer fields are left unchanged (or inherited). If Defaults is true all fields are first reset to the library defaults.

type Constructor

type Constructor struct {
	// The maximum number of significant digits of the result of a
	// calculation or base conversion. 1 to maxDigits.
	Precision int64
	// The rounding mode used when rounding to Precision. 0 to 8.
	Rounding int64
	// The modulo mode used by Mod. 0 to 9.
	Modulo int64
	// The exponent value at and beneath which String returns exponential
	// notation. 0 to -expLimit.
	ToExpNeg int64
	// The exponent value at and above which String returns exponential
	// notation. 0 to expLimit.
	ToExpPos int64
	// The minimum exponent value, beneath which underflow to zero occurs.
	MinE int64
	// The maximum exponent value, above which overflow to Infinity occurs.
	MaxE int64
	// Whether to use cryptographically-secure random number generation.
	Crypto bool
	// contains filtered or unexported fields
}

Constructor holds the configuration of a Decimal constructor, mirroring the per-constructor properties (precision, rounding, ...) of decimal.js. Use Default for the package-level default constructor, or create new constructors with Constructor.Clone.

func (*Constructor) Abs

func (c *Constructor) Abs(x any) *Decimal

Abs returns |x|.

func (*Constructor) Acos

func (c *Constructor) Acos(x any) *Decimal

Acos returns the arccosine in radians of x.

func (*Constructor) Acosh

func (c *Constructor) Acosh(x any) *Decimal

Acosh returns the inverse hyperbolic cosine of x.

func (*Constructor) Add

func (c *Constructor) Add(x, y any) *Decimal

Add returns x + y.

func (*Constructor) Asin

func (c *Constructor) Asin(x any) *Decimal

Asin returns the arcsine in radians of x.

func (*Constructor) Asinh

func (c *Constructor) Asinh(x any) *Decimal

Asinh returns the inverse hyperbolic sine of x.

func (*Constructor) Atan

func (c *Constructor) Atan(x any) *Decimal

Atan returns the arctangent in radians of x.

func (*Constructor) Atan2

func (c *Constructor) Atan2(y, x any) *Decimal

Atan2 returns the arctangent in radians of y/x in the range -pi to pi, rounded to the constructor's precision.

func (*Constructor) Atanh

func (c *Constructor) Atanh(x any) *Decimal

Atanh returns the inverse hyperbolic tangent of x.

func (*Constructor) Cbrt

func (c *Constructor) Cbrt(x any) *Decimal

Cbrt returns the cube root of x.

func (*Constructor) Ceil

func (c *Constructor) Ceil(x any) *Decimal

Ceil returns x rounded to an integer using RoundCeil.

func (*Constructor) Clamp

func (c *Constructor) Clamp(x, min, max any) *Decimal

Clamp returns x clamped to the range delineated by min and max.

func (*Constructor) Clone

func (c *Constructor) Clone(cfg *Config) *Constructor

Clone creates and returns a new constructor with the same configuration as c, optionally overridden by cfg.

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	// Clones are how you get a constructor whose settings differ from Default.
	base := mk()
	round := base.Clone(&dec.Config{Precision: dec.I64(8)})
	x := round.New("1.00000001")
	fmt.Println(x.Times(x)) // rounds to 8 significant digits
}
Output:
1

func (*Constructor) Config

func (c *Constructor) Config(cfg *Config) *Constructor

Config applies the given configuration settings to c. It panics with a "[DecimalError]" error on invalid values.

func (*Constructor) Cos

func (c *Constructor) Cos(x any) *Decimal

Cos returns the cosine of x (radians).

func (*Constructor) Cosh

func (c *Constructor) Cosh(x any) *Decimal

Cosh returns the hyperbolic cosine of x.

func (*Constructor) Div

func (c *Constructor) Div(x, y any) *Decimal

Div returns x / y.

func (*Constructor) Exp

func (c *Constructor) Exp(x any) *Decimal

Exp returns e^x.

func (*Constructor) Floor

func (c *Constructor) Floor(x any) *Decimal

Floor returns x rounded to an integer using RoundFloor.

func (*Constructor) Hypot

func (c *Constructor) Hypot(args ...any) *Decimal

Hypot returns the square root of the sum of the squares of the arguments.

func (*Constructor) Ln

func (c *Constructor) Ln(x any) *Decimal

Ln returns the natural logarithm of x.

func (*Constructor) Log

func (c *Constructor) Log(x any, y ...any) *Decimal

Log returns the logarithm of x to the base y (default: 10).

func (*Constructor) Log2

func (c *Constructor) Log2(x any) *Decimal

Log2 returns the base 2 logarithm of x.

func (*Constructor) Log10

func (c *Constructor) Log10(x any) *Decimal

Log10 returns the base 10 logarithm of x.

func (*Constructor) Max

func (c *Constructor) Max(args ...any) *Decimal

Max returns the maximum of the arguments.

func (*Constructor) Min

func (c *Constructor) Min(args ...any) *Decimal

Min returns the minimum of the arguments.

func (*Constructor) Mod

func (c *Constructor) Mod(x, y any) *Decimal

Mod returns x modulo y.

func (*Constructor) Mul

func (c *Constructor) Mul(x, y any) *Decimal

Mul returns x * y.

func (*Constructor) New

func (c *Constructor) New(v any) *Decimal

New returns a new Decimal whose value is parsed from v, which may be a *Decimal (copied), a string (decimal, or 0x/0b/0o-prefixed with optional fraction and binary exponent), an integer of any width, or a float. It panics with a "[DecimalError]" error for invalid values.

func (*Constructor) Pow

func (c *Constructor) Pow(x, y any) *Decimal

Pow returns x raised to the power y.

func (*Constructor) Random

func (c *Constructor) Random(sds ...int64) *Decimal

Random returns a new Decimal with a pseudo-random value equal to or greater than 0 and less than 1, and with sd, or Precision if sd is omitted, significant digits.

func (*Constructor) Round

func (c *Constructor) Round(x any) *Decimal

Round returns x rounded to an integer using the constructor's rounding mode.

func (*Constructor) Set

func (c *Constructor) Set(cfg *Config) *Constructor

Set is an alias of Config.

func (*Constructor) Sign

func (c *Constructor) Sign(x any) float64

Sign returns 1 if x > 0, -1 if x < 0, 0 if x is 0, -0 if x is -0, NaN otherwise.

func (*Constructor) Sin

func (c *Constructor) Sin(x any) *Decimal

Sin returns the sine of x (radians).

func (*Constructor) Sinh

func (c *Constructor) Sinh(x any) *Decimal

Sinh returns the hyperbolic sine of x.

func (*Constructor) Sqrt

func (c *Constructor) Sqrt(x any) *Decimal

Sqrt returns the square root of x.

func (*Constructor) Sub

func (c *Constructor) Sub(x, y any) *Decimal

Sub returns x - y.

func (*Constructor) Sum

func (c *Constructor) Sum(args ...any) *Decimal

Sum returns the sum of the arguments. Only the result is rounded, not the intermediate calculations.

func (*Constructor) Tan

func (c *Constructor) Tan(x any) *Decimal

Tan returns the tangent of x (radians).

func (*Constructor) Tanh

func (c *Constructor) Tanh(x any) *Decimal

Tanh returns the hyperbolic tangent of x.

func (*Constructor) Trunc

func (c *Constructor) Trunc(x any) *Decimal

Trunc returns x truncated to an integer.

type Decimal

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

Decimal is an arbitrary-precision decimal floating-point number.

The zero value is not ready for use; obtain values through Constructor.New (or the package-level New which uses Default).

func New

func New(v any) *Decimal

New returns a new Decimal parsed from v using the Default constructor. v may be a *Decimal, string, any integer type or float.

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	fmt.Println(mk().New("1.5").Plus(mk().New("2.25")))
	fmt.Println(mk().New(42).Div(mk().New(8)))
	fmt.Println(mk().New("0x1p4"))
}
Output:
3.75
5.25
16

func (*Decimal) Abs

func (x *Decimal) Abs() *Decimal

Abs returns a new Decimal whose value is |x|.

func (*Decimal) AbsoluteValue

func (x *Decimal) AbsoluteValue() *Decimal

AbsoluteValue returns |x|.

func (*Decimal) Acos

func (x *Decimal) Acos() *Decimal

Acos returns the arccosine in radians of x, rounded to the constructor's precision. Domain: [-1, 1]; Range: [0, pi].

func (*Decimal) Acosh

func (x *Decimal) Acosh() *Decimal

Acosh returns the inverse hyperbolic cosine of x, rounded to the constructor's precision.

func (*Decimal) Add

func (x *Decimal) Add(y any) *Decimal

Add is an alias of Plus.

func (*Decimal) Asin

func (x *Decimal) Asin() *Decimal

Asin returns the arcsine in radians of x, rounded to the constructor's precision. Domain: [-1, 1]; Range: [-pi/2, pi/2].

func (*Decimal) Asinh

func (x *Decimal) Asinh() *Decimal

Asinh returns the inverse hyperbolic sine of x, rounded to the constructor's precision.

func (*Decimal) Atan

func (x *Decimal) Atan() *Decimal

Atan returns the arctangent in radians of x, rounded to the constructor's precision. Range: [-pi/2, pi/2].

func (*Decimal) Atanh

func (x *Decimal) Atanh() *Decimal

Atanh returns the inverse hyperbolic tangent of x, rounded to the constructor's precision.

func (*Decimal) Cbrt

func (x *Decimal) Cbrt() *Decimal

Cbrt returns a new Decimal whose value is the cube root of x, rounded to the constructor's precision.

func (*Decimal) Ceil

func (x *Decimal) Ceil() *Decimal

Ceil returns a new Decimal whose value is x rounded to a whole number in the direction of positive Infinity.

func (*Decimal) Clamp

func (x *Decimal) Clamp(min, max any) *Decimal

Clamp returns x clamped to the range delineated by min and max.

func (*Decimal) ClampedTo

func (x *Decimal) ClampedTo(min, max any) *Decimal

ClampedTo returns a new Decimal whose value is x clamped between min and max.

func (*Decimal) Cmp

func (x *Decimal) Cmp(y any) float64

Cmp returns

1    if the value of x is greater than the value of y,
-1   if the value of x is less than the value of y,
0    if they have the same value,
NaN  if the value of either is NaN.

func (*Decimal) ComparedTo

func (x *Decimal) ComparedTo(y any) float64

ComparedTo compares x and y.

func (*Decimal) Cos

func (x *Decimal) Cos() *Decimal

Cos returns the cosine of x (in radians), rounded to the constructor's precision.

func (*Decimal) Cosh

func (x *Decimal) Cosh() *Decimal

Cosh returns the hyperbolic cosine of x, rounded to the constructor's precision.

func (*Decimal) Cosine

func (x *Decimal) Cosine() *Decimal

Cosine returns the cosine of x in radians.

func (*Decimal) CubeRoot

func (x *Decimal) CubeRoot() *Decimal

CubeRoot returns the cube root of x.

func (*Decimal) DecimalPlaces

func (x *Decimal) DecimalPlaces() float64

DecimalPlaces returns the number of decimal places of x.

func (*Decimal) Div

func (x *Decimal) Div(y any) *Decimal

Div returns x / y rounded to the constructor's precision.

func (*Decimal) DivToInt

func (x *Decimal) DivToInt(y any) *Decimal

DivToInt returns a new Decimal whose value is the integer part of x / y, rounded to the constructor's precision.

func (*Decimal) DividedBy

func (x *Decimal) DividedBy(y any) *Decimal

DividedBy returns x / y.

func (*Decimal) DividedToIntegerBy

func (x *Decimal) DividedToIntegerBy(y any) *Decimal

DividedToIntegerBy returns the quotient of the division of x by y rounded to a whole number.

func (*Decimal) Dp

func (x *Decimal) Dp() float64

Dp returns the number of decimal places of x, or NaN if x is not finite.

func (*Decimal) Eq

func (x *Decimal) Eq(y any) bool

Eq returns true if x == y.

func (*Decimal) Equals

func (x *Decimal) Equals(y any) bool

Equals returns true if x == y.

func (*Decimal) Exp

func (x *Decimal) Exp() *Decimal

Exp returns e^x rounded to the constructor's precision.

func (*Decimal) Float64

func (x *Decimal) Float64() float64

Float64 returns the value of x converted to a float64. Zero keeps its sign. NaN converts to NaN, ±Infinity to ±Inf.

func (*Decimal) Floor

func (x *Decimal) Floor() *Decimal

Floor returns a new Decimal whose value is x rounded to a whole number in the direction of negative Infinity.

func (*Decimal) GreaterThan

func (x *Decimal) GreaterThan(y any) bool

GreaterThan returns true if x > y.

func (*Decimal) GreaterThanOrEqualTo

func (x *Decimal) GreaterThanOrEqualTo(y any) bool

GreaterThanOrEqualTo returns true if x >= y.

func (*Decimal) Gt

func (x *Decimal) Gt(y any) bool

Gt returns true if x > y.

func (*Decimal) Gte

func (x *Decimal) Gte(y any) bool

Gte returns true if x >= y.

func (*Decimal) HyperbolicCosine

func (x *Decimal) HyperbolicCosine() *Decimal

HyperbolicCosine returns the hyperbolic cosine of x.

func (*Decimal) HyperbolicSine

func (x *Decimal) HyperbolicSine() *Decimal

HyperbolicSine returns the hyperbolic sine of x.

func (*Decimal) HyperbolicTangent

func (x *Decimal) HyperbolicTangent() *Decimal

HyperbolicTangent returns the hyperbolic tangent of x.

func (*Decimal) InverseCosine

func (x *Decimal) InverseCosine() *Decimal

InverseCosine returns the arccosine of x in radians.

func (*Decimal) InverseHyperbolicCosine

func (x *Decimal) InverseHyperbolicCosine() *Decimal

InverseHyperbolicCosine returns the inverse hyperbolic cosine of x.

func (*Decimal) InverseHyperbolicSine

func (x *Decimal) InverseHyperbolicSine() *Decimal

InverseHyperbolicSine returns the inverse hyperbolic sine of x.

func (*Decimal) InverseHyperbolicTangent

func (x *Decimal) InverseHyperbolicTangent() *Decimal

InverseHyperbolicTangent returns the inverse hyperbolic tangent of x.

func (*Decimal) InverseSine

func (x *Decimal) InverseSine() *Decimal

InverseSine returns the arcsine of x in radians.

func (*Decimal) InverseTangent

func (x *Decimal) InverseTangent() *Decimal

InverseTangent returns the arctangent of x in radians.

func (*Decimal) IsFinite

func (x *Decimal) IsFinite() bool

IsFinite returns true if x is a finite number.

func (*Decimal) IsInt

func (x *Decimal) IsInt() bool

IsInt returns true if x is a finite integer.

func (*Decimal) IsInteger

func (x *Decimal) IsInteger() bool

IsInteger returns true if x is an integer.

func (*Decimal) IsNaN

func (x *Decimal) IsNaN() bool

IsNaN returns true if x is NaN.

func (*Decimal) IsNeg

func (x *Decimal) IsNeg() bool

IsNeg returns true if x is negative.

func (*Decimal) IsNegative

func (x *Decimal) IsNegative() bool

IsNegative returns true if x is negative.

func (*Decimal) IsPos

func (x *Decimal) IsPos() bool

IsPos returns true if x is positive.

func (*Decimal) IsPositive

func (x *Decimal) IsPositive() bool

IsPositive returns true if x is positive.

func (*Decimal) IsZero

func (x *Decimal) IsZero() bool

IsZero returns true if x is 0 or -0.

func (*Decimal) LessThan

func (x *Decimal) LessThan(y any) bool

LessThan returns true if x < y.

func (*Decimal) LessThanOrEqualTo

func (x *Decimal) LessThanOrEqualTo(y any) bool

LessThanOrEqualTo returns true if x <= y.

func (*Decimal) Ln

func (x *Decimal) Ln() *Decimal

Ln returns the natural logarithm of x rounded to the constructor's precision.

func (*Decimal) Log

func (x *Decimal) Log(bases ...any) *Decimal

Log returns the logarithm of x to the given base (default base 10), rounded to the constructor's precision.

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	c := mk()
	p := c.New("1000")
	fmt.Println(c.Log10(p))
	fmt.Println(p.Log(c.New("10")))
}
Output:
3
3

func (*Decimal) Logarithm

func (x *Decimal) Logarithm(bases ...any) *Decimal

Logarithm returns the logarithm of x to the given base (default 10).

func (*Decimal) Lt

func (x *Decimal) Lt(y any) bool

Lt returns true if x < y.

func (*Decimal) Lte

func (x *Decimal) Lte(y any) bool

Lte returns true if x <= y.

func (Decimal) MarshalJSON

func (x Decimal) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler: the value is marshalled as a JSON string matching the valueOf() representation (decimal.js toJSON behaviour).

Example
package main

import (
	"encoding/json"
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	type invoice struct {
		Total dec.Decimal `json:"total"`
	}
	inv := invoice{Total: *mk().New("1234.5000")}
	b, _ := json.Marshal(inv)
	fmt.Println(string(b))
}
Output:
{"total":"1234.5"}

func (Decimal) MarshalText

func (x Decimal) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler. The textual form is the valueOf() representation (the same string ValueOf returns), so text encodings round-trip exactly, including an explicit "-0".

func (*Decimal) Minus

func (x *Decimal) Minus(y any) *Decimal

Minus returns x - y rounded to the constructor's precision.

func (*Decimal) Mod

func (x *Decimal) Mod(y any) *Decimal

Mod returns x modulo y, rounded to the constructor's precision. The result depends on the constructor's modulo mode.

func (*Decimal) Modulo

func (x *Decimal) Modulo(y any) *Decimal

Modulo returns x modulo y.

func (*Decimal) Mul

func (x *Decimal) Mul(y any) *Decimal

Mul is an alias of Times.

func (*Decimal) NaturalExponential

func (x *Decimal) NaturalExponential() *Decimal

NaturalExponential returns e^x.

func (*Decimal) NaturalLogarithm

func (x *Decimal) NaturalLogarithm() *Decimal

NaturalLogarithm returns the natural logarithm (base e) of x.

func (*Decimal) Neg

func (x *Decimal) Neg() *Decimal

Neg returns a new Decimal whose value is -x.

func (*Decimal) Negated

func (x *Decimal) Negated() *Decimal

Negated returns -x.

func (*Decimal) Plus

func (x *Decimal) Plus(y any) *Decimal

Plus returns x + y rounded to the constructor's precision.

func (*Decimal) Pow

func (x *Decimal) Pow(y any) *Decimal

Pow returns a new Decimal whose value is x raised to the power y, rounded to the constructor's precision.

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	c := mk()
	fmt.Println(c.New("2").Pow(c.New("10")))
	fmt.Println(c.New("0").Pow(c.New("0")))
	fmt.Println(c.New("-1").Pow(c.New("0.5")))
}
Output:
1024
1
NaN

func (*Decimal) Precision

func (x *Decimal) Precision(z ...bool) float64

Precision returns the number of significant digits of x. If z is true, trailing integer zeros are counted.

func (*Decimal) Round

func (x *Decimal) Round() *Decimal

Round returns a new Decimal whose value is x rounded to a whole number using the constructor's rounding mode.

func (*Decimal) Scan

func (x *Decimal) Scan(src any) error

Scan implements database/sql.Scanner. src must be a type accepted by Constructor.New (string, integer or float64), a []byte (treated as its decimal string), a *Decimal (copied), or nil (stored as NaN to represent SQL NULL). The receiver's constructor settings are used for parsing.

func (*Decimal) Sd

func (x *Decimal) Sd(z ...bool) float64

Sd returns the number of significant digits of x, or NaN if x is not finite. If z is true, integer-part trailing zeros are counted.

func (*Decimal) Sin

func (x *Decimal) Sin() *Decimal

Sin returns the sine of x (in radians), rounded to the constructor's precision.

func (*Decimal) Sine

func (x *Decimal) Sine() *Decimal

Sine returns the sine of x in radians.

func (*Decimal) Sinh

func (x *Decimal) Sinh() *Decimal

Sinh returns the hyperbolic sine of x, rounded to the constructor's precision.

func (*Decimal) Sqrt

func (x *Decimal) Sqrt() *Decimal

Sqrt returns a new Decimal whose value is the square root of x, rounded to the constructor's precision.

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	c := mk()
	fmt.Println(c.New("2").Sqrt())
	fmt.Println(c.New("16").Sqrt())
	fmt.Println(c.New("-1").Sqrt())
}
Output:
1.4142135623730950488
4
NaN

func (*Decimal) SquareRoot

func (x *Decimal) SquareRoot() *Decimal

SquareRoot returns the square root of x.

func (*Decimal) String

func (x *Decimal) String() string

String returns a string representing the value of x, using exponential notation if the exponent is >= ToExpPos or <= ToExpNeg.

func (*Decimal) Sub

func (x *Decimal) Sub(y any) *Decimal

Sub is an alias of Minus.

func (*Decimal) Tan

func (x *Decimal) Tan() *Decimal

Tan returns the tangent of x (in radians), rounded to the constructor's precision.

func (*Decimal) Tangent

func (x *Decimal) Tangent() *Decimal

Tangent returns the tangent of x in radians.

func (*Decimal) Tanh

func (x *Decimal) Tanh() *Decimal

Tanh returns the hyperbolic tangent of x, rounded to the constructor's precision.

func (*Decimal) Times

func (x *Decimal) Times(y any) *Decimal

Times returns x * y rounded to the constructor's precision.

func (*Decimal) ToBinary

func (x *Decimal) ToBinary(sd ...int64) string

ToBinary returns a string representing x in base 2, rounded to sd significant digits using rm. If sd is present the result uses binary exponential notation, otherwise fixed-point.

func (*Decimal) ToDP

func (x *Decimal) ToDP(args ...int64) *Decimal

ToDP returns a new Decimal whose value is x rounded to a maximum of dp decimal places using rounding mode rm (or the constructor's rounding mode if omitted).

func (*Decimal) ToDecimalPlaces

func (x *Decimal) ToDecimalPlaces(args ...int64) *Decimal

ToDecimalPlaces returns a new Decimal rounded to dp decimal places using rounding mode rm (default: Constructor.Rounding).

func (*Decimal) ToExponential

func (x *Decimal) ToExponential(args ...int64) string

ToExponential returns a string representing x in exponential notation rounded to dp fixed decimal places using rounding mode rm (or the constructor's rounding mode if omitted).

func (*Decimal) ToFixed

func (x *Decimal) ToFixed(args ...int64) string

ToFixed returns a string representing x in normal (fixed-point) notation to dp fixed decimal places, rounded using rm (or the constructor's rounding mode if omitted).

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	c := mk()
	n := c.New("3.14159265358979323846")
	fmt.Println(n.ToFixed(4))
	fmt.Println(n.ToExponential(3))
	fmt.Println(n.ToPrecision(6))
}
Output:
3.1416
3.142e+0
3.14159

func (*Decimal) ToFraction

func (x *Decimal) ToFraction(maxD ...any) []*Decimal

ToFraction returns x as a simple fraction with integer numerator and denominator, each a new Decimal. The denominator will be positive and at most maxD (if omitted, the lowest denominator representing x exactly).

func (*Decimal) ToHex

func (x *Decimal) ToHex(sd ...int64) string

ToHex returns a string representing x in base 16. See ToBinary.

func (*Decimal) ToHexadecimal

func (x *Decimal) ToHexadecimal(sd ...int64) string

ToHexadecimal returns the hexadecimal representation of x to sd significant digits (default: Constructor.Precision).

func (*Decimal) ToJSON

func (x *Decimal) ToJSON() string

ToJSON returns the JSON-compatible string representation of x, as decimal.js defines toJSON as an alias of valueOf.

func (*Decimal) ToNearest

func (x *Decimal) ToNearest(y any, rm ...int64) *Decimal

ToNearest returns a new Decimal whose value is the nearest multiple of y in the direction of rounding mode rm (or the constructor's rounding mode if omitted).

func (*Decimal) ToOctal

func (x *Decimal) ToOctal(sd ...int64) string

ToOctal returns a string representing x in base 8. See ToBinary.

func (*Decimal) ToPower

func (x *Decimal) ToPower(y any) *Decimal

ToPower returns x raised to the power y.

func (*Decimal) ToPrecision

func (x *Decimal) ToPrecision(args ...int64) string

ToPrecision returns a string representing x rounded to sd significant digits. Exponential notation is used if necessary.

func (*Decimal) ToSD

func (x *Decimal) ToSD(args ...int64) *Decimal

ToSD returns a new Decimal whose value is x rounded to a maximum of sd significant digits using rounding mode rm (or the constructor's precision and rounding mode if omitted).

func (*Decimal) ToSignificantDigits

func (x *Decimal) ToSignificantDigits(args ...int64) *Decimal

ToSignificantDigits returns x rounded to sd significant digits using rounding mode rm (default: Constructor.Rounding).

func (*Decimal) ToString

func (x *Decimal) ToString() string

ToString returns the string representation of x. Unlike ValueOf, for a negative zero the minus sign is omitted, mirroring decimal.js toString.

func (*Decimal) Trunc

func (x *Decimal) Trunc() *Decimal

Trunc returns a new Decimal whose value is x truncated to a whole number.

func (*Decimal) Truncated

func (x *Decimal) Truncated() *Decimal

Truncated returns the value of x truncated to a whole number.

func (*Decimal) UnmarshalText

func (x *Decimal) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler. b is parsed as a decimal string using the constructor the receiver belongs to (or Default when the receiver is a zero-value Decimal). It returns an error if b is not a valid representation.

func (*Decimal) Value

func (x *Decimal) Value() (driver.Value, error)

Value implements driver.Valuer for database/sql. The value is returned as a string in the valueOf() representation so no precision is lost. A nil receiver returns nil (SQL NULL).

func (*Decimal) ValueOf

func (x *Decimal) ValueOf() string

ValueOf is like String, but negative zero includes the minus sign.

Example
package main

import (
	"fmt"

	dec "github.com/iSundram/decimal-go"
)

// mk returns a cloned constructor with the decimal.js default settings. Each
// example builds its own so that examples are deterministic regardless of
// which tests ran before them on whatever shared Default.
func mk() *dec.Constructor {
	return dec.Default.Clone(&dec.Config{
		Precision: dec.I64(20),
		Rounding:  dec.I64(dec.RoundHalfUp),
		ToExpNeg:  dec.I64(-7),
		ToExpPos:  dec.I64(21),
		MaxE:      dec.I64(9e15),
		MinE:      dec.I64(-9e15),
	})
}

func main() {
	// String omits the sign of -0; ValueOf keeps it (decimal.js parity).
	c := mk()
	x := c.New("-0")
	fmt.Println(x.String())
	fmt.Println(x.ValueOf())
}
Output:
0
-0

Directories

Path Synopsis
xvalid generates operation results from decimal-go and prints one line per case using exactly the same format as xvalidate/x.js.
xvalid generates operation results from decimal-go and prints one line per case using exactly the same format as xvalidate/x.js.

Jump to

Keyboard shortcuts

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