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 ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func I64(v int64) *int64
- func IsDecimal(v any) bool
- type Config
- type Constructor
- func (c *Constructor) Abs(x any) *Decimal
- func (c *Constructor) Acos(x any) *Decimal
- func (c *Constructor) Acosh(x any) *Decimal
- func (c *Constructor) Add(x, y any) *Decimal
- func (c *Constructor) Asin(x any) *Decimal
- func (c *Constructor) Asinh(x any) *Decimal
- func (c *Constructor) Atan(x any) *Decimal
- func (c *Constructor) Atan2(y, x any) *Decimal
- func (c *Constructor) Atanh(x any) *Decimal
- func (c *Constructor) Cbrt(x any) *Decimal
- func (c *Constructor) Ceil(x any) *Decimal
- func (c *Constructor) Clamp(x, min, max any) *Decimal
- func (c *Constructor) Clone(cfg *Config) *Constructor
- func (c *Constructor) Config(cfg *Config) *Constructor
- func (c *Constructor) Cos(x any) *Decimal
- func (c *Constructor) Cosh(x any) *Decimal
- func (c *Constructor) Div(x, y any) *Decimal
- func (c *Constructor) Exp(x any) *Decimal
- func (c *Constructor) Floor(x any) *Decimal
- func (c *Constructor) Hypot(args ...any) *Decimal
- func (c *Constructor) Ln(x any) *Decimal
- func (c *Constructor) Log(x any, y ...any) *Decimal
- func (c *Constructor) Log2(x any) *Decimal
- func (c *Constructor) Log10(x any) *Decimal
- func (c *Constructor) Max(args ...any) *Decimal
- func (c *Constructor) Min(args ...any) *Decimal
- func (c *Constructor) Mod(x, y any) *Decimal
- func (c *Constructor) Mul(x, y any) *Decimal
- func (c *Constructor) New(v any) *Decimal
- func (c *Constructor) Pow(x, y any) *Decimal
- func (c *Constructor) Random(sds ...int64) *Decimal
- func (c *Constructor) Round(x any) *Decimal
- func (c *Constructor) Set(cfg *Config) *Constructor
- func (c *Constructor) Sign(x any) float64
- func (c *Constructor) Sin(x any) *Decimal
- func (c *Constructor) Sinh(x any) *Decimal
- func (c *Constructor) Sqrt(x any) *Decimal
- func (c *Constructor) Sub(x, y any) *Decimal
- func (c *Constructor) Sum(args ...any) *Decimal
- func (c *Constructor) Tan(x any) *Decimal
- func (c *Constructor) Tanh(x any) *Decimal
- func (c *Constructor) Trunc(x any) *Decimal
- type Decimal
- func (x *Decimal) Abs() *Decimal
- func (x *Decimal) AbsoluteValue() *Decimal
- func (x *Decimal) Acos() *Decimal
- func (x *Decimal) Acosh() *Decimal
- func (x *Decimal) Add(y any) *Decimal
- func (x *Decimal) Asin() *Decimal
- func (x *Decimal) Asinh() *Decimal
- func (x *Decimal) Atan() *Decimal
- func (x *Decimal) Atanh() *Decimal
- func (x *Decimal) Cbrt() *Decimal
- func (x *Decimal) Ceil() *Decimal
- func (x *Decimal) Clamp(min, max any) *Decimal
- func (x *Decimal) ClampedTo(min, max any) *Decimal
- func (x *Decimal) Cmp(y any) float64
- func (x *Decimal) ComparedTo(y any) float64
- func (x *Decimal) Cos() *Decimal
- func (x *Decimal) Cosh() *Decimal
- func (x *Decimal) Cosine() *Decimal
- func (x *Decimal) CubeRoot() *Decimal
- func (x *Decimal) DecimalPlaces() float64
- func (x *Decimal) Div(y any) *Decimal
- func (x *Decimal) DivToInt(y any) *Decimal
- func (x *Decimal) DividedBy(y any) *Decimal
- func (x *Decimal) DividedToIntegerBy(y any) *Decimal
- func (x *Decimal) Dp() float64
- func (x *Decimal) Eq(y any) bool
- func (x *Decimal) Equals(y any) bool
- func (x *Decimal) Exp() *Decimal
- func (x *Decimal) Float64() float64
- func (x *Decimal) Floor() *Decimal
- func (x *Decimal) GreaterThan(y any) bool
- func (x *Decimal) GreaterThanOrEqualTo(y any) bool
- func (x *Decimal) Gt(y any) bool
- func (x *Decimal) Gte(y any) bool
- func (x *Decimal) HyperbolicCosine() *Decimal
- func (x *Decimal) HyperbolicSine() *Decimal
- func (x *Decimal) HyperbolicTangent() *Decimal
- func (x *Decimal) InverseCosine() *Decimal
- func (x *Decimal) InverseHyperbolicCosine() *Decimal
- func (x *Decimal) InverseHyperbolicSine() *Decimal
- func (x *Decimal) InverseHyperbolicTangent() *Decimal
- func (x *Decimal) InverseSine() *Decimal
- func (x *Decimal) InverseTangent() *Decimal
- func (x *Decimal) IsFinite() bool
- func (x *Decimal) IsInt() bool
- func (x *Decimal) IsInteger() bool
- func (x *Decimal) IsNaN() bool
- func (x *Decimal) IsNeg() bool
- func (x *Decimal) IsNegative() bool
- func (x *Decimal) IsPos() bool
- func (x *Decimal) IsPositive() bool
- func (x *Decimal) IsZero() bool
- func (x *Decimal) LessThan(y any) bool
- func (x *Decimal) LessThanOrEqualTo(y any) bool
- func (x *Decimal) Ln() *Decimal
- func (x *Decimal) Log(bases ...any) *Decimal
- func (x *Decimal) Logarithm(bases ...any) *Decimal
- func (x *Decimal) Lt(y any) bool
- func (x *Decimal) Lte(y any) bool
- func (x Decimal) MarshalJSON() ([]byte, error)
- func (x Decimal) MarshalText() ([]byte, error)
- func (x *Decimal) Minus(y any) *Decimal
- func (x *Decimal) Mod(y any) *Decimal
- func (x *Decimal) Modulo(y any) *Decimal
- func (x *Decimal) Mul(y any) *Decimal
- func (x *Decimal) NaturalExponential() *Decimal
- func (x *Decimal) NaturalLogarithm() *Decimal
- func (x *Decimal) Neg() *Decimal
- func (x *Decimal) Negated() *Decimal
- func (x *Decimal) Plus(y any) *Decimal
- func (x *Decimal) Pow(y any) *Decimal
- func (x *Decimal) Precision(z ...bool) float64
- func (x *Decimal) Round() *Decimal
- func (x *Decimal) Scan(src any) error
- func (x *Decimal) Sd(z ...bool) float64
- func (x *Decimal) Sin() *Decimal
- func (x *Decimal) Sine() *Decimal
- func (x *Decimal) Sinh() *Decimal
- func (x *Decimal) Sqrt() *Decimal
- func (x *Decimal) SquareRoot() *Decimal
- func (x *Decimal) String() string
- func (x *Decimal) Sub(y any) *Decimal
- func (x *Decimal) Tan() *Decimal
- func (x *Decimal) Tangent() *Decimal
- func (x *Decimal) Tanh() *Decimal
- func (x *Decimal) Times(y any) *Decimal
- func (x *Decimal) ToBinary(sd ...int64) string
- func (x *Decimal) ToDP(args ...int64) *Decimal
- func (x *Decimal) ToDecimalPlaces(args ...int64) *Decimal
- func (x *Decimal) ToExponential(args ...int64) string
- func (x *Decimal) ToFixed(args ...int64) string
- func (x *Decimal) ToFraction(maxD ...any) []*Decimal
- func (x *Decimal) ToHex(sd ...int64) string
- func (x *Decimal) ToHexadecimal(sd ...int64) string
- func (x *Decimal) ToJSON() string
- func (x *Decimal) ToNearest(y any, rm ...int64) *Decimal
- func (x *Decimal) ToOctal(sd ...int64) string
- func (x *Decimal) ToPower(y any) *Decimal
- func (x *Decimal) ToPrecision(args ...int64) string
- func (x *Decimal) ToSD(args ...int64) *Decimal
- func (x *Decimal) ToSignificantDigits(args ...int64) *Decimal
- func (x *Decimal) ToString() string
- func (x *Decimal) Trunc() *Decimal
- func (x *Decimal) Truncated() *Decimal
- func (x *Decimal) UnmarshalText(b []byte) error
- func (x *Decimal) Value() (driver.Value, error)
- func (x *Decimal) ValueOf() string
Examples ¶
Constants ¶
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 ¶
var Default = defaultConstructor()
Default is the package-level default Decimal constructor, mirroring the default Decimal export of decimal.js.
Functions ¶
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) 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) 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) 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) 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) 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 ¶
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) AbsoluteValue ¶
AbsoluteValue returns |x|.
func (*Decimal) Acos ¶
Acos returns the arccosine in radians of x, rounded to the constructor's precision. Domain: [-1, 1]; Range: [0, pi].
func (*Decimal) Acosh ¶
Acosh returns the inverse hyperbolic cosine of x, rounded to the constructor's precision.
func (*Decimal) Asin ¶
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 ¶
Asinh returns the inverse hyperbolic sine of x, rounded to the constructor's precision.
func (*Decimal) Atan ¶
Atan returns the arctangent in radians of x, rounded to the constructor's precision. Range: [-pi/2, pi/2].
func (*Decimal) Atanh ¶
Atanh returns the inverse hyperbolic tangent of x, rounded to the constructor's precision.
func (*Decimal) Cbrt ¶
Cbrt returns a new Decimal whose value is the cube root of x, rounded to the constructor's precision.
func (*Decimal) Ceil ¶
Ceil returns a new Decimal whose value is x rounded to a whole number in the direction of positive Infinity.
func (*Decimal) ClampedTo ¶
ClampedTo returns a new Decimal whose value is x clamped between min and max.
func (*Decimal) Cmp ¶
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 ¶
ComparedTo compares x and y.
func (*Decimal) Cos ¶
Cos returns the cosine of x (in radians), rounded to the constructor's precision.
func (*Decimal) Cosh ¶
Cosh returns the hyperbolic cosine of x, rounded to the constructor's precision.
func (*Decimal) DecimalPlaces ¶
DecimalPlaces returns the number of decimal places of x.
func (*Decimal) DivToInt ¶
DivToInt returns a new Decimal whose value is the integer part of x / y, rounded to the constructor's precision.
func (*Decimal) DividedToIntegerBy ¶
DividedToIntegerBy returns the quotient of the division of x by y rounded to a whole number.
func (*Decimal) 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 ¶
Floor returns a new Decimal whose value is x rounded to a whole number in the direction of negative Infinity.
func (*Decimal) GreaterThan ¶
GreaterThan returns true if x > y.
func (*Decimal) GreaterThanOrEqualTo ¶
GreaterThanOrEqualTo returns true if x >= y.
func (*Decimal) HyperbolicCosine ¶
HyperbolicCosine returns the hyperbolic cosine of x.
func (*Decimal) HyperbolicSine ¶
HyperbolicSine returns the hyperbolic sine of x.
func (*Decimal) HyperbolicTangent ¶
HyperbolicTangent returns the hyperbolic tangent of x.
func (*Decimal) InverseCosine ¶
InverseCosine returns the arccosine of x in radians.
func (*Decimal) InverseHyperbolicCosine ¶
InverseHyperbolicCosine returns the inverse hyperbolic cosine of x.
func (*Decimal) InverseHyperbolicSine ¶
InverseHyperbolicSine returns the inverse hyperbolic sine of x.
func (*Decimal) InverseHyperbolicTangent ¶
InverseHyperbolicTangent returns the inverse hyperbolic tangent of x.
func (*Decimal) InverseSine ¶
InverseSine returns the arcsine of x in radians.
func (*Decimal) InverseTangent ¶
InverseTangent returns the arctangent of x in radians.
func (*Decimal) IsNegative ¶
IsNegative returns true if x is negative.
func (*Decimal) IsPositive ¶
IsPositive returns true if x is positive.
func (*Decimal) LessThanOrEqualTo ¶
LessThanOrEqualTo returns true if x <= y.
func (*Decimal) Log ¶
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) MarshalJSON ¶
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 ¶
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) Mod ¶
Mod returns x modulo y, rounded to the constructor's precision. The result depends on the constructor's modulo mode.
func (*Decimal) NaturalExponential ¶
NaturalExponential returns e^x.
func (*Decimal) NaturalLogarithm ¶
NaturalLogarithm returns the natural logarithm (base e) of x.
func (*Decimal) Pow ¶
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 ¶
Precision returns the number of significant digits of x. If z is true, trailing integer zeros are counted.
func (*Decimal) Round ¶
Round returns a new Decimal whose value is x rounded to a whole number using the constructor's rounding mode.
func (*Decimal) Scan ¶
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 ¶
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 ¶
Sin returns the sine of x (in radians), rounded to the constructor's precision.
func (*Decimal) Sinh ¶
Sinh returns the hyperbolic sine of x, rounded to the constructor's precision.
func (*Decimal) Sqrt ¶
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 ¶
SquareRoot returns the square root of x.
func (*Decimal) String ¶
String returns a string representing the value of x, using exponential notation if the exponent is >= ToExpPos or <= ToExpNeg.
func (*Decimal) Tan ¶
Tan returns the tangent of x (in radians), rounded to the constructor's precision.
func (*Decimal) Tanh ¶
Tanh returns the hyperbolic tangent of x, rounded to the constructor's precision.
func (*Decimal) ToBinary ¶
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 ¶
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 ¶
ToDecimalPlaces returns a new Decimal rounded to dp decimal places using rounding mode rm (default: Constructor.Rounding).
func (*Decimal) ToExponential ¶
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 ¶
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 ¶
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) ToHexadecimal ¶
ToHexadecimal returns the hexadecimal representation of x to sd significant digits (default: Constructor.Precision).
func (*Decimal) ToJSON ¶
ToJSON returns the JSON-compatible string representation of x, as decimal.js defines toJSON as an alias of valueOf.
func (*Decimal) ToNearest ¶
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) ToPrecision ¶
ToPrecision returns a string representing x rounded to sd significant digits. Exponential notation is used if necessary.
func (*Decimal) ToSD ¶
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 ¶
ToSignificantDigits returns x rounded to sd significant digits using rounding mode rm (default: Constructor.Rounding).
func (*Decimal) ToString ¶
ToString returns the string representation of x. Unlike ValueOf, for a negative zero the minus sign is omitted, mirroring decimal.js toString.
func (*Decimal) UnmarshalText ¶
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 ¶
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 ¶
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