dfp

package
v0.6.1-0...-e229e97 Latest Latest
Warning

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

Go to latest
Published: May 7, 2020 License: Apache-2.0 Imports: 11 Imported by: 0

README

Package dfp

Representation

Value is a positive decimal floating-point number. It currently uses a uint64 value as a data type, where 8 bits are used for exponent and 56 for mantissa.

   63      55                                                     0
   ________|_______________________________________________________
   eeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

Value can be useful for representing numbers like prices in financial services. Negative numbers aren't currently supported.

Usage

To get a value use one of From{Uint64, String, Float, MantAndExp} :

	v, err := dfp.FromString("1.23456")
	if err != nil {
		panic(err)
	}

See value_example_test.go for more examples.

Documentation

Overview

Package dfp implements a decimal floating-point number, where both mantissa and exponent are stored in a single number. Can be used to represent currency rates with up to 16 digits of precision.

Index

Examples

Constants

View Source
const (
	// FormatString marshals values as strings, like `"1234.5678"`
	FormatString = iota
	// FormatFloat marshals values as floats, like `1234.5678`.
	FormatFloat
	// FormatJSONObject marshals values with mantissa and exponent, like `{"m":123,"e":-5}`.
	FormatJSONObject

	// JSONModeCompact will choose the shortest form between FormatString and FormatJSONObject.
	JSONModeCompact = -1
)

Variables

View Source
var (
	// Max is the maximum possible fixed-point value.
	Max = fromMantAndExp(maxMantissa, maxExponent)
	// Min is the minimum possible fixed-point value.
	Min = fromMantAndExp(minMantissa, minExponent)
)
View Source
var (
	// JSONMode defines the way all values are marshaled into json.
	// Either Format* constants or JSONModeCompact can be used.
	// This variable is not thread-safe, so this should not be changed concurently.
	JSONMode = JSONModeCompact
)

Functions

This section is empty.

Types

type Value

type Value number

Value is a positive decimal floating-point number. It currently uses a uint64 value as a data type, where 8 bits are used for exponent and 56 for mantissa.

63      55                                                     0
________|_______________________________________________________
eeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

Value can be useful for representing numbers like prices in financial services.

Example
v1, err := FromString("1.23456")
if err != nil {
	panic(err)
}
fmt.Printf("v1 as a float = %v, mantissa = %v, uint64 = %v\n", v1.Float64(), v1.MantUint64(), v1.Uint64())

v2, err := FromFloat64(1.23456)
if err != nil {
	panic(err)
}
fmt.Printf("value from string: %s, value from float: %s, values are equal: %v\n", v1.String(), v2.String(), v1.Eq(v2))

v3 := FromMantAndExp(12345, -4)
fmt.Printf("uint64 values for -6 exp %d, %d\n", v1.ToExp(-6).MantUint64(), v3.ToExp(-6).MantUint64())

data, err := json.Marshal(v1)
if err != nil {
	panic(err)
}
fmt.Printf("json for value: %s\n", string(data))

JSONMode = FormatJSONObject
data, err = json.Marshal(v1)
if err != nil {
	panic(err)
}
fmt.Printf("json for value and JSONModeME: %s\n", string(data))

v4, err := FromString("1234560")
if err != nil {
	panic(err)
}
fmt.Printf("%s + %s = %s\n", v4.String(), v1.String(), v4.Add(v1).String())

sub, neg := v4.Sub(v1)
fmt.Printf("%s - %s = ", v4.String(), v1.String())
if neg {
	fmt.Printf("-")
}
fmt.Printf("%s\n", sub)

sub, neg = v1.Sub(v4)
fmt.Printf("%s - %s = ", v1.String(), v4.String())
if neg {
	fmt.Printf("-")
}
fmt.Printf("%s\n", sub)

fmt.Printf("%s * %s = %s\n", v1.String(), v4.String(), v1.Mul(v4).String())

a, b := FromMantAndExp(45, -2), FromMantAndExp(15, -2)
fmt.Printf("%s / %s = %s\n", a.String(), b.String(), a.Div(b))

a, b = FromMantAndExp(15, 0), FromMantAndExp(7, 0)
q, r := a.DivMod(b, 3)
fmt.Printf("%s / %s = %s (%s), prec = 3\n", a.String(), b.String(), q, r)
q, r = a.DivMod(b, 2)
fmt.Printf("%s / %s = %s (%s), prec = 2\n", a.String(), b.String(), q, r)
q, r = a.DivMod(b, 0)
fmt.Printf("%s / %s = %s (%s), prec = 0\n", a.String(), b.String(), q, r)

a, b = FromMantAndExp(15, 4), FromMantAndExp(7, 1)
q, r = a.DivMod(b, 2)
fmt.Printf("%s / %s = %s (%s), prec = 2\n", a.String(), b.String(), q, r)
Output:

v1 as a float = 1.23456, mantissa = 123456, uint64 = 1
value from string: 1.23456, value from float: 1.23456, values are equal: true
uint64 values for -6 exp 1234560, 1234500
json for value: "1.23456"
json for value and JSONModeME: {"m":123456,"e":-5}
1234560 + 1.23456 = 1234561.23456
1234560 - 1.23456 = 1234558.76544
1.23456 - 1234560 = -1234558.76544
1.23456 * 1234560 = 1524138.3936
0.45 / 0.15 = 3
15 / 7 = 2.142 (0.006), prec = 3
15 / 7 = 2.14 (0.02), prec = 2
15 / 7 = 2 (1), prec = 0
150000 / 70 = 2142.85 (0.5), prec = 2

func FromFloat64

func FromFloat64(v float64) (Value, error)

FromFloat64 returns a value for given float64 value. Returns an error for nagative values, infinities, and not-a-numbers.

func FromMantAndExp

func FromMantAndExp(mant uint64, exp int32) Value

FromMantAndExp returns a value for given mantissa and exponent. If the number cannot be precisely represented, the least significant digits will be truncated.

func FromString

func FromString(s string) (Value, error)

FromString parses a string into a value.

func FromUint64

func FromUint64(v uint64) Value

FromUint64 returns a value for given uint64 number. If the number cannot be precisely represented, the least significant digits will be truncated.

func MustFromFloat64

func MustFromFloat64(f float64) Value

MustFromFloat64 returns a value for given float64 value. It panics on an error.

func MustFromString

func MustFromString(s string) Value

MustFromString parses a string into a value. It panics on an error.

func (Value) Add

func (v Value) Add(other Value) Value

Add returns the sum of two values. If the resulting mantissa overflows max mantissa, the least significant digits will be truncated. If the result overflows Max, Max is returned.

func (Value) Ceil

func (v Value) Ceil(prec int) Value

Ceil returns the nearest value greater than or equal to v that has prec decimal places. Note that prec can be negative.

func (Value) Cmp

func (v Value) Cmp(other Value) int

Cmp compares two values. Returns -1 if a < b, 0 if a == b, 1 if a > b.

func (Value) Div

func (v Value) Div(other Value) Value

Div calculates a/b. If b == 0, Div panics. First, it tries to perform integer division, and if the remainder is zero, returns the result. Otherwise, it returns the result of a float64 division.

func (Value) DivMod

func (v Value) DivMod(other Value, prec int) (quo, rem Value)

DivMod calculates such quo and rem, that a = b * quo + rem. If b == 0, Div panics. Quo will be rounded to prec digits. Notice that prec can be negative.

func (Value) Eq

func (v Value) Eq(other Value) bool

Eq returns true if both values represent the same number.

func (Value) Float64

func (v Value) Float64() float64

Float64 returns a float64 value.

func (Value) Floor

func (v Value) Floor(prec int) Value

Floor returns the nearest value less than or equal to v that has prec decimal places. Note that prec can be negative.

func (Value) Format

func (v Value) Format(f fmt.State, c rune)

Format implements fmt.Formatter and allows to format values as a string.

'f', 's' will produce a decimal string, e.g. 123.456
'e', 'v' will produce scientific notation, e.g. 123456e7

func (Value) GoString

func (v Value) GoString() string

GoString returns debug string representation.

func (Value) IsZero

func (v Value) IsZero() bool

IsZero returns true if the value has zero mantissa.

func (Value) MantUint64

func (v Value) MantUint64() uint64

MantUint64 returns v's mantissa as is.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON marshals value according to current JSONMode. See JSONMode and JSONMode* constants.

func (Value) Mul

func (v Value) Mul(other Value) Value

Mul returns v * other. If the result underflows Min, zero is returned. If the rsult overflows Max, Max is returned. If the resulting mantissa overflows max mantissa, the least significant digits will be truncated.

func (Value) Normalized

func (v Value) Normalized() Value

Normalized eliminates trailing zeros in the mantissa. The process increases the exponent, and stops if it exceeds the maximum possible exponent, so that it is possible, that the mantissa will still have trailing zeros.

func (Value) Round

func (v Value) Round(prec int) Value

Round rounds the value to prec decimal places. Note that prec can be negative.

func (Value) String

func (v Value) String() string

String returns a string representation of the value.

func (Value) Sub

func (v Value) Sub(other Value) (Value, bool)

Sub returns |a-b| and a boolean flag indicating that the result is negative.

func (Value) ToExp

func (v Value) ToExp(exp int32) Value

ToExp changes the mantissa of v so, that v = m * 10e'exp'. As a result, mantissa can lose some digits in precision, become zero, or Max.

func (Value) Uint64

func (v Value) Uint64() uint64

Uint64 returns the value as a uint64 number.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a string, float, or an object into a value.

Jump to

Keyboard shortcuts

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