utils

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Ipv4Regex = `^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`
	Ipv6Regex = `` /* 663-byte string literal not displayed */
)
View Source
var (
	// DefaultTagName is the default tag name for struct fields which provides
	// a more granular to tweak certain structs. Lookup the necessary functions
	// for more info.
	DefaultTagName = "structs" // struct's field default tag name
)
View Source
var DivisionPrecision = 16

DivisionPrecision is the number of decimal places in the result when it doesn't divide exactly.

Example:

d1 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
d1.String() // output: "0.6666666666666667"
d2 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(30000))
d2.String() // output: "0.0000666666666667"
d3 := decimal.NewFromFloat(20000).Div(decimal.NewFromFloat(3))
d3.String() // output: "6666.6666666666666667"
decimal.DivisionPrecision = 3
d4 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
d4.String() // output: "0.667"
View Source
var ExpMaxIterations = 1000

ExpMaxIterations specifies the maximum number of iterations needed to calculate precise natural exponent value using ExpHullAbrham method.

View Source
var MarshalJSONWithoutQuotes = false

MarshalJSONWithoutQuotes should be set to true if you want the decimal to be JSON marshaled as a number, instead of as a string. WARNING: this is dangerous for decimals with many digits, since many JSON unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754 double-precision floating point numbers, which means you can potentially silently lose precision.

View Source
var Zero = New(0, 1)

Zero constant, to make computations faster. Zero should never be compared with == or != directly, please use decimal.Equal or decimal.Cmp instead.

Functions

func Append

func Append(slice interface{}, elements interface{}) []interface{}

func Byte2Any

func Byte2Any(b []byte, t reflect.Type) interface{}

func Byte2Str

func Byte2Str(b []byte) string

func ChEnLength

func ChEnLength(str string) int

func CheckIP

func CheckIP(ip string) string

func CheckMobile

func CheckMobile(phone string) bool

func CheckPasswordRule

func CheckPasswordRule(password string) bool

func FillMap

func FillMap(s interface{}, out map[string]interface{})

FillMap is the same as Map. Instead of returning the output, it fills the given map.

func HasZero

func HasZero(s interface{}) bool

HasZero returns true if any field is equal to a zero value. For more info refer to Struct types HasZero() method. It panics if s's kind is not struct.

func IsEmpty

func IsEmpty(data interface{}) bool

func IsIpv4 added in v0.2.7

func IsIpv4(ip string) bool

func IsIpv6 added in v0.2.7

func IsIpv6(ip string) bool

func IsStruct

func IsStruct(s interface{}) bool

IsStruct returns true if the given variable is a struct or a pointer to struct.

func IsZero

func IsZero(s interface{}) bool

IsZero returns true if all fields is equal to a zero value. For more info refer to Struct types IsZero() method. It panics if s's kind is not struct.

func JSONToYAML added in v0.2.7

func JSONToYAML(j []byte) ([]byte, error)

Convert JSON to YAML.

func Json2ListMapForFile added in v0.2.7

func Json2ListMapForFile(filePath string) ([]map[string]interface{}, error)

func Json2ListMapForFileConv added in v0.2.7

func Json2ListMapForFileConv(filePath string) ([]map[string]interface{}, error)

func Json2MapForFile added in v0.2.7

func Json2MapForFile(filePath string) (map[string]interface{}, error)

func Json2MapForFileConv added in v0.2.7

func Json2MapForFileConv(filePath string) (map[string]interface{}, error)

func List2String added in v0.1.7

func List2String(slice []interface{}) string

func List2Strings added in v0.1.7

func List2Strings(slice []interface{}) []string

func Map

func Map(s interface{}) map[string]interface{}

Map converts the given struct to a map[string]interface{}. For more info refer to Struct types Map() method. It panics if s's kind is not struct.

func Marshal added in v0.2.7

func Marshal(o interface{}) ([]byte, error)

Marshals the object into JSON then converts JSON to YAML and returns the YAML.

func Name

func Name(s interface{}) string

Name returns the structs's type name within its package. It returns an empty string for unnamed types. It panics if s's kind is not struct.

func Names

func Names(s interface{}) []string

Names returns a slice of field names. For more info refer to Struct types Names() method. It panics if s's kind is not struct.

func Order added in v0.1.7

func Order(keys []interface{}, key string, objs []interface{}) []interface{}

func OrderByte added in v0.1.7

func OrderByte(keys []interface{}, key string, objs []interface{}) []byte

func OrderStruct added in v0.1.7

func OrderStruct(keys []interface{}, key string, objs []struct{}) []struct{}

func RemoveDuplicateElement

func RemoveDuplicateElement(slice []interface{}) []interface{}

func RescalePair

func RescalePair(d1 Decimal, d2 Decimal) (Decimal, Decimal)

RescalePair rescales two decimals to common exponential value (minimal exp of both decimals)

func Str2Array added in v0.2.7

func Str2Array(s string) []string

func Str2Float

func Str2Float(s string) float64

func Str2Uint64

func Str2Uint64(s string) uint64

func StrLength

func StrLength(str string) int

func StrTrim

func StrTrim(str string) string

func Struct2Map

func Struct2Map(model interface{}, tagName string) map[string]interface{}

func Struct2MapNoZero

func Struct2MapNoZero(model interface{}, tagName string) map[string]interface{}

func SubnetMatch

func SubnetMatch(subnet string) (string, string, error)

func Unmarshal added in v0.2.7

func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error

Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object, optionally configuring the behavior of the JSON unmarshal.

func UnmarshalStrict added in v0.2.7

func UnmarshalStrict(y []byte, o interface{}, opts ...JSONOpt) error

UnmarshalStrict is like Unmarshal except that any mapping keys that are duplicates will result in an error. To also be strict about unknown fields, add the DisallowUnknownFields option.

func Values

func Values(s interface{}) []interface{}

Values converts the given struct to a []interface{}. For more info refer to Struct types Values() method. It panics if s's kind is not struct.

func YAMLToJSON added in v0.2.7

func YAMLToJSON(y []byte) ([]byte, error)

YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML, passing JSON through this method should be a no-op.

Things YAML can do that are not supported by JSON:

  • In YAML you can have binary and null keys in your maps. These are invalid in JSON. (int and float keys are converted to strings.)
  • Binary data in YAML with the !!binary tag is not supported. If you want to use binary data with this library, encode the data as base64 as usual but do not use the !!binary tag in your YAML. This will ensure the original base64 encoded data makes it all the way through to the JSON.

For strict decoding of YAML, use YAMLToJSONStrict.

func YAMLToJSONStrict added in v0.2.7

func YAMLToJSONStrict(y []byte) ([]byte, error)

YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding, returning an error on any duplicate field names.

func Yaml2JsonForByte added in v0.2.7

func Yaml2JsonForByte(content []byte) (map[string]interface{}, error)

func Yaml2JsonForFile added in v0.2.7

func Yaml2JsonForFile(filePath string) (map[string]interface{}, error)

func Yaml2JsonForString added in v0.2.7

func Yaml2JsonForString(content string) (map[string]interface{}, error)

Types

type Decimal

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

Decimal represents a fixed-point decimal. It is immutable. number = value * 10 ^ exp

func Avg

func Avg(first Decimal, rest ...Decimal) Decimal

Avg returns the average value of the provided first and rest Decimals

func Max

func Max(first Decimal, rest ...Decimal) Decimal

Max returns the largest Decimal that was passed in the arguments.

To call this function with an array, you must do:

Max(arr[0], arr[1:]...)

This makes it harder to accidentally call Max with 0 arguments.

func Min

func Min(first Decimal, rest ...Decimal) Decimal

Min returns the smallest Decimal that was passed in the arguments.

To call this function with an array, you must do:

Min(arr[0], arr[1:]...)

This makes it harder to accidentally call Min with 0 arguments.

func New

func New(value int64, exp int32) Decimal

Create returns a new fixed-point decimal, value * 10 ^ exp.

func NewFromBigInt

func NewFromBigInt(value *big.Int, exp int32) Decimal

NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp

func NewFromFloat

func NewFromFloat(value float64) Decimal

NewFromFloat converts a float64 to Decimal.

The converted number will contain the number of significant digits that can be represented in a float with reliable roundtrip. This is typically 15 digits, but may be more in some cases. See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.

For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.

NOTE: this will panic on NaN, +/-inf

func NewFromFloat32

func NewFromFloat32(value float32) Decimal

NewFromFloat32 converts a float32 to Decimal.

The converted number will contain the number of significant digits that can be represented in a float with reliable roundtrip. This is typically 6-8 digits depending on the input. See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.

For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.

NOTE: this will panic on NaN, +/-inf

func NewFromFloatWithExponent

func NewFromFloatWithExponent(value float64, exp int32) Decimal

NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary number of fractional digits.

Example:

NewFromFloatWithExponent(123.456, -2).String() // output: "123.46"

func NewFromFormattedString

func NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error)

NewFromFormattedString returns a new Decimal from a formatted string representation. The second argument - replRegexp, is a regular expression that is used to find characters that should be removed from given decimal string representation. All matched characters will be replaced with an empty string.

Example:

r := regexp.MustCompile("[$,]")
d1, err := NewFromFormattedString("$5,125.99", r)

r2 := regexp.MustCompile("[_]")
d2, err := NewFromFormattedString("1_000_000", r2)

r3 := regexp.MustCompile("[USD\\s]")
d3, err := NewFromFormattedString("5000 USD", r3)

func NewFromInt

func NewFromInt(value int64) Decimal

NewFromInt converts a int64 to Decimal.

Example:

NewFromInt(123).String() // output: "123"
NewFromInt(-10).String() // output: "-10"

func NewFromInt32

func NewFromInt32(value int32) Decimal

NewFromInt32 converts a int32 to Decimal.

Example:

NewFromInt(123).String() // output: "123"
NewFromInt(-10).String() // output: "-10"

func NewFromString

func NewFromString(value string) (Decimal, error)

NewFromString returns a new Decimal from a string representation. Trailing zeroes are not trimmed.

Example:

d, err := NewFromString("-123.45")
d2, err := NewFromString(".0001")
d3, err := NewFromString("1.47000")

func RequireFromString

func RequireFromString(value string) Decimal

RequireFromString returns a new Decimal from a string representation or panics if NewFromString would have returned an error.

Example:

d := RequireFromString("-123.45")
d2 := RequireFromString(".0001")

func Sum

func Sum(first Decimal, rest ...Decimal) Decimal

Sum returns the combined total of the provided first and rest Decimals

func (Decimal) Abs

func (d Decimal) Abs() Decimal

Abs returns the absolute value of the decimal.

func (Decimal) Add

func (d Decimal) Add(d2 Decimal) Decimal

Add returns d + d2.

func (Decimal) Atan

func (d Decimal) Atan() Decimal

Atan returns the arctangent, in radians, of x.

func (Decimal) BigFloat

func (d Decimal) BigFloat() *big.Float

BigFloat returns decimal as BigFloat. Be aware that casting decimal to BigFloat might cause a loss of precision.

func (Decimal) BigInt

func (d Decimal) BigInt() *big.Int

BigInt returns integer component of the decimal as a BigInt.

func (Decimal) Ceil

func (d Decimal) Ceil() Decimal

Ceil returns the nearest integer value greater than or equal to d.

func (Decimal) Cmp

func (d Decimal) Cmp(d2 Decimal) int

Cmp compares the numbers represented by d and d2 and returns:

-1 if d <  d2
 0 if d == d2
+1 if d >  d2

func (Decimal) Coefficient

func (d Decimal) Coefficient() *big.Int

Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()

func (Decimal) CoefficientInt64

func (d Decimal) CoefficientInt64() int64

CoefficientInt64 returns the coefficient of the decimal as int64. It is scaled by 10^Exponent() If coefficient cannot be represented in an int64, the result will be undefined.

func (Decimal) Copy

func (d Decimal) Copy() Decimal

Copy returns a copy of decimal with the same value and exponent, but a different pointer to value.

func (Decimal) Cos

func (d Decimal) Cos() Decimal

Cos returns the cosine of the radian argument x.

func (Decimal) Div

func (d Decimal) Div(d2 Decimal) Decimal

Div returns d / d2. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point.

func (Decimal) DivRound

func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal

DivRound divides and rounds to a given precision i.e. to an integer multiple of 10^(-precision)

for a positive quotient digit 5 is rounded up, away from 0
if the quotient is negative then digit 5 is rounded down, away from 0

Note that precision<0 is allowed as input.

func (Decimal) Equal

func (d Decimal) Equal(d2 Decimal) bool

Equal returns whether the numbers represented by d and d2 are equal.

func (Decimal) Equals

func (d Decimal) Equals(d2 Decimal) bool

Equals is deprecated, please use Equal method instead

func (Decimal) ExpHullAbrham

func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error)

ExpHullAbrham calculates the natural exponent of decimal (e to the power of d) using Hull-Abraham algorithm. OverallPrecision argument specifies the overall precision of the result (integer part + decimal part).

ExpHullAbrham is faster than ExpTaylor for small precision values, but it is much slower for large precision values.

Example:

NewFromFloat(26.1).ExpHullAbrham(2).String()    // output: "220000000000"
NewFromFloat(26.1).ExpHullAbrham(20).String()   // output: "216314672147.05767284"

func (Decimal) ExpTaylor

func (d Decimal) ExpTaylor(precision int32) (Decimal, error)

ExpTaylor calculates the natural exponent of decimal (e to the power of d) using Taylor series expansion. Precision argument specifies how precise the result must be (number of digits after decimal point). Negative precision is allowed.

ExpTaylor is much faster for large precision values than ExpHullAbrham.

Example:

d, err := NewFromFloat(26.1).ExpTaylor(2).String()
d.String()  // output: "216314672147.06"

NewFromFloat(26.1).ExpTaylor(20).String()
d.String()  // output: "216314672147.05767284062928674083"

NewFromFloat(26.1).ExpTaylor(-10).String()
d.String()  // output: "220000000000"

func (Decimal) Exponent

func (d Decimal) Exponent() int32

Exponent returns the exponent, or scale component of the decimal.

func (Decimal) Float64

func (d Decimal) Float64() (f float64, exact bool)

Float64 returns the nearest float64 value for d and a bool indicating whether f represents d exactly. For more details, see the documentation for big.Rat.Float64

func (Decimal) Floor

func (d Decimal) Floor() Decimal

Floor returns the nearest integer value less than or equal to d.

func (*Decimal) GobDecode

func (d *Decimal) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface for gob serialization.

func (Decimal) GobEncode

func (d Decimal) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface for gob serialization.

func (Decimal) GreaterThan

func (d Decimal) GreaterThan(d2 Decimal) bool

GreaterThan (GT) returns true when d is greater than d2.

func (Decimal) GreaterThanOrEqual

func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool

GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.

func (Decimal) InexactFloat64

func (d Decimal) InexactFloat64() float64

InexactFloat64 returns the nearest float64 value for d. It doesn't indicate if the returned value represents d exactly.

func (Decimal) IntPart

func (d Decimal) IntPart() int64

IntPart returns the integer component of the decimal.

func (Decimal) IsInteger

func (d Decimal) IsInteger() bool

IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false.

func (Decimal) IsNegative

func (d Decimal) IsNegative() bool

IsNegative return

true if d < 0
false if d == 0
false if d > 0

func (Decimal) IsPositive

func (d Decimal) IsPositive() bool

IsPositive return

true if d > 0
false if d == 0
false if d < 0

func (Decimal) IsZero

func (d Decimal) IsZero() bool

IsZero return

true if d == 0
false if d > 0
false if d < 0

func (Decimal) LessThan

func (d Decimal) LessThan(d2 Decimal) bool

LessThan (LT) returns true when d is less than d2.

func (Decimal) LessThanOrEqual

func (d Decimal) LessThanOrEqual(d2 Decimal) bool

LessThanOrEqual (LTE) returns true when d is less than or equal to d2.

func (Decimal) MarshalBinary

func (d Decimal) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Decimal) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface.

func (Decimal) MarshalText

func (d Decimal) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface for XML serialization.

func (Decimal) Mod

func (d Decimal) Mod(d2 Decimal) Decimal

Mod returns d % d2.

func (Decimal) Mul

func (d Decimal) Mul(d2 Decimal) Decimal

Mul returns d * d2.

func (Decimal) Neg

func (d Decimal) Neg() Decimal

Neg returns -d.

func (Decimal) NumDigits

func (d Decimal) NumDigits() int

NumDigits returns the number of digits of the decimal coefficient (d.Value) Note: Current implementation is extremely slow for large decimals and/or decimals with large fractional part

func (Decimal) Pow

func (d Decimal) Pow(d2 Decimal) Decimal

Pow returns d to the power d2

func (Decimal) QuoRem

func (d Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal)

QuoRem does division with remainder d.QuoRem(d2,precision) returns quotient q and remainder r such that

d = d2 * q + r, q an integer multiple of 10^(-precision)
0 <= r < abs(d2) * 10 ^(-precision) if d>=0
0 >= r > -abs(d2) * 10 ^(-precision) if d<0

Note that precision<0 is allowed as input.

func (Decimal) Rat

func (d Decimal) Rat() *big.Rat

Rat returns a rational number representation of the decimal.

func (Decimal) Round

func (d Decimal) Round(places int32) Decimal

Round rounds the decimal to places decimal places. If places < 0, it will round the integer part to the nearest 10^(-places).

Example:

NewFromFloat(5.45).Round(1).String() // output: "5.5"
NewFromFloat(545).Round(-1).String() // output: "550"

func (Decimal) RoundBank

func (d Decimal) RoundBank(places int32) Decimal

RoundBank rounds the decimal to places decimal places. If the final digit to round is equidistant from the nearest two integers the rounded value is taken as the even number

If places < 0, it will round the integer part to the nearest 10^(-places).

Examples:

NewFromFloat(5.45).RoundBank(1).String() // output: "5.4"
NewFromFloat(545).RoundBank(-1).String() // output: "540"
NewFromFloat(5.46).RoundBank(1).String() // output: "5.5"
NewFromFloat(546).RoundBank(-1).String() // output: "550"
NewFromFloat(5.55).RoundBank(1).String() // output: "5.6"
NewFromFloat(555).RoundBank(-1).String() // output: "560"

func (Decimal) RoundCash

func (d Decimal) RoundCash(interval uint8) Decimal

RoundCash aka Cash/Penny/öre rounding rounds decimal to a specific interval. The amount payable for a cash transaction is rounded to the nearest multiple of the minimum currency unit available. The following intervals are available: 5, 10, 25, 50 and 100; any other number throws a panic.

  5:   5 cent rounding 3.43 => 3.45
 10:  10 cent rounding 3.45 => 3.50 (5 gets rounded up)
 25:  25 cent rounding 3.41 => 3.50
 50:  50 cent rounding 3.75 => 4.00
100: 100 cent rounding 3.50 => 4.00

For more details: https://en.wikipedia.org/wiki/Cash_rounding

func (Decimal) RoundCeil

func (d Decimal) RoundCeil(places int32) Decimal

RoundCeil rounds the decimal towards +infinity.

Example:

NewFromFloat(545).RoundCeil(-2).String()   // output: "600"
NewFromFloat(500).RoundCeil(-2).String()   // output: "500"
NewFromFloat(1.1001).RoundCeil(2).String() // output: "1.11"
NewFromFloat(-1.454).RoundCeil(1).String() // output: "-1.5"

func (Decimal) RoundDown

func (d Decimal) RoundDown(places int32) Decimal

RoundDown rounds the decimal towards zero.

Example:

NewFromFloat(545).RoundDown(-2).String()   // output: "500"
NewFromFloat(-500).RoundDown(-2).String()   // output: "-500"
NewFromFloat(1.1001).RoundDown(2).String() // output: "1.1"
NewFromFloat(-1.454).RoundDown(1).String() // output: "-1.5"

func (Decimal) RoundFloor

func (d Decimal) RoundFloor(places int32) Decimal

RoundFloor rounds the decimal towards -infinity.

Example:

NewFromFloat(545).RoundFloor(-2).String()   // output: "500"
NewFromFloat(-500).RoundFloor(-2).String()   // output: "-500"
NewFromFloat(1.1001).RoundFloor(2).String() // output: "1.1"
NewFromFloat(-1.454).RoundFloor(1).String() // output: "-1.4"

func (Decimal) RoundUp

func (d Decimal) RoundUp(places int32) Decimal

RoundUp rounds the decimal away from zero.

Example:

NewFromFloat(545).RoundUp(-2).String()   // output: "600"
NewFromFloat(500).RoundUp(-2).String()   // output: "500"
NewFromFloat(1.1001).RoundUp(2).String() // output: "1.11"
NewFromFloat(-1.454).RoundUp(1).String() // output: "-1.4"

func (*Decimal) Scan

func (d *Decimal) Scan(value interface{}) error

Scan implements the sql.Scanner interface for database deserialization.

func (Decimal) Shift

func (d Decimal) Shift(shift int32) Decimal

Shift shifts the decimal in base 10. It shifts left when shift is positive and right if shift is negative. In simpler terms, the given value for shift is added to the exponent of the decimal.

func (Decimal) Sign

func (d Decimal) Sign() int

Sign returns:

-1 if d <  0
 0 if d == 0
+1 if d >  0

func (Decimal) Sin

func (d Decimal) Sin() Decimal

Sin returns the sine of the radian argument x.

func (Decimal) String

func (d Decimal) String() string

String returns the string representation of the decimal with the fixed point.

Example:

d := Create(-12345, -3)
println(d.String())

Output:

-12.345

func (Decimal) StringFixed

func (d Decimal) StringFixed(places int32) string

StringFixed returns a rounded fixed-point string with places digits after the decimal point.

Example:

NewFromFloat(0).StringFixed(2) // output: "0.00"
NewFromFloat(0).StringFixed(0) // output: "0"
NewFromFloat(5.45).StringFixed(0) // output: "5"
NewFromFloat(5.45).StringFixed(1) // output: "5.5"
NewFromFloat(5.45).StringFixed(2) // output: "5.45"
NewFromFloat(5.45).StringFixed(3) // output: "5.450"
NewFromFloat(545).StringFixed(-1) // output: "550"

func (Decimal) StringFixedBank

func (d Decimal) StringFixedBank(places int32) string

StringFixedBank returns a banker rounded fixed-point string with places digits after the decimal point.

Example:

NewFromFloat(0).StringFixedBank(2) // output: "0.00"
NewFromFloat(0).StringFixedBank(0) // output: "0"
NewFromFloat(5.45).StringFixedBank(0) // output: "5"
NewFromFloat(5.45).StringFixedBank(1) // output: "5.4"
NewFromFloat(5.45).StringFixedBank(2) // output: "5.45"
NewFromFloat(5.45).StringFixedBank(3) // output: "5.450"
NewFromFloat(545).StringFixedBank(-1) // output: "540"

func (Decimal) StringFixedCash

func (d Decimal) StringFixedCash(interval uint8) string

StringFixedCash returns a Swedish/Cash rounded fixed-point string. For more details see the documentation at function RoundCash.

func (Decimal) StringScaled

func (d Decimal) StringScaled(exp int32) string

StringScaled first scales the decimal then calls .String() on it. NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.

func (Decimal) Sub

func (d Decimal) Sub(d2 Decimal) Decimal

Sub returns d - d2.

func (Decimal) Tan

func (d Decimal) Tan() Decimal

Tan returns the tangent of the radian argument x.

func (Decimal) Truncate

func (d Decimal) Truncate(precision int32) Decimal

Truncate truncates off digits from the number, without rounding.

NOTE: precision is the last digit that will not be truncated (must be >= 0).

Example:

decimal.NewFromString("123.456").Truncate(2).String() // "123.45"

func (*Decimal) UnmarshalBinary

func (d *Decimal) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation is already used when encoding to text, this method stores that string as []byte

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Decimal) UnmarshalText

func (d *Decimal) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.

func (Decimal) Value

func (d Decimal) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database serialization.

type Field

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

Field represents a single struct field that encapsulates high level functions around the field.

func Fields

func Fields(s interface{}) []*Field

Fields returns a slice of *Field. For more info refer to Struct types Fields() method. It panics if s's kind is not struct.

func (*Field) Field

func (f *Field) Field(name string) *Field

Field returns the field from a nested struct. It panics if the nested struct is not exported or if the field was not found.

func (*Field) FieldOk

func (f *Field) FieldOk(name string) (*Field, bool)

FieldOk returns the field from a nested struct. The boolean returns whether the field was found (true) or not (false).

func (*Field) Fields

func (f *Field) Fields() []*Field

Fields returns a slice of Fields. This is particular handy to get the fields of a nested struct . A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field *http.Request `structs:"-"`

It panics if field is not exported or if field's kind is not struct

func (*Field) IsEmbedded

func (f *Field) IsEmbedded() bool

IsEmbedded returns true if the given field is an anonymous field (embedded)

func (*Field) IsExported

func (f *Field) IsExported() bool

IsExported returns true if the given field is exported.

func (*Field) IsZero

func (f *Field) IsZero() bool

IsZero returns true if the given field is not initialized (has a zero value). It panics if the field is not exported.

func (*Field) Kind

func (f *Field) Kind() reflect.Kind

Kind returns the fields kind, such as "string", "map", "bool", etc ..

func (*Field) Name

func (f *Field) Name() string

Name returns the name of the given field

func (*Field) Set

func (f *Field) Set(val interface{}) error

Set sets the field to given value v. It returns an error if the field is not settable (not addressable or not exported) or if the given value's type doesn't match the fields type.

func (*Field) Tag

func (f *Field) Tag(key string) string

Tag returns the value associated with key in the tag string. If there is no such key in the tag, Tag returns the empty string.

func (*Field) Value

func (f *Field) Value() interface{}

Value returns the underlying value of the field. It panics if the field is not exported.

func (*Field) Zero

func (f *Field) Zero() error

Zero sets the field to its zero value. It returns an error if the field is not settable (not addressable or not exported).

type JSONOpt added in v0.2.7

type JSONOpt func(*json.Decoder) *json.Decoder

JSONOpt is a decoding option for decoding from JSON format.

type NullDecimal

type NullDecimal struct {
	Decimal Decimal
	Valid   bool
}

NullDecimal represents a nullable decimal with compatibility for scanning null values from the database.

func NewNullDecimal

func NewNullDecimal(d Decimal) NullDecimal

func (NullDecimal) MarshalJSON

func (d NullDecimal) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (NullDecimal) MarshalText

func (d NullDecimal) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface for XML serialization.

func (*NullDecimal) Scan

func (d *NullDecimal) Scan(value interface{}) error

Scan implements the sql.Scanner interface for database deserialization.

func (*NullDecimal) UnmarshalJSON

func (d *NullDecimal) UnmarshalJSON(decimalBytes []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*NullDecimal) UnmarshalText

func (d *NullDecimal) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization

func (NullDecimal) Value

func (d NullDecimal) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database serialization.

type Struct

type Struct struct {
	TagName string
	// contains filtered or unexported fields
}

Struct encapsulates a struct type to provide several high level functions around the struct.

func Create

func Create(s interface{}) *Struct

Create returns a new *Struct with the struct s. It panics if the s's kind is not struct.

func (*Struct) Field

func (s *Struct) Field(name string) *Field

Field returns a new Field struct that provides several high level functions around a single struct field entity. It panics if the field is not found.

func (*Struct) FieldOk

func (s *Struct) FieldOk(name string) (*Field, bool)

FieldOk returns a new Field struct that provides several high level functions around a single struct field entity. The boolean returns true if the field was found.

func (*Struct) Fields

func (s *Struct) Fields() []*Field

Fields returns a slice of Fields. A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

It panics if s's kind is not struct.

func (*Struct) FillMap

func (s *Struct) FillMap(out map[string]interface{})

FillMap is the same as Map. Instead of returning the output, it fills the given map.

func (*Struct) HasZero

func (s *Struct) HasZero() bool

HasZero returns true if a field in a struct is not initialized (zero value). A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

A value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Field is not processed further by this package.
Field time.Time     `structs:"myName,omitnested"`
Field *http.Request `structs:",omitnested"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected. It panics if s's kind is not struct.

func (*Struct) IsZero

func (s *Struct) IsZero() bool

IsZero returns true if all fields in a struct is a zero value (not initialized) A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

A value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Field is not processed further by this package.
Field time.Time     `structs:"myName,omitnested"`
Field *http.Request `structs:",omitnested"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected. It panics if s's kind is not struct.

func (*Struct) Map

func (s *Struct) Map() map[string]interface{}

Map converts the given struct to a map[string]interface{}, where the keys of the map are the field names and the values of the map the associated values of the fields. The default key string is the struct field name but can be changed in the struct field's tag value. The "structs" key in the struct's field tag value is the key name. Example:

// Field appears in map as key "myName".
Name string `structs:"myName"`

A tag value with the content of "-" ignores that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

A tag value with the content of "string" uses the stringer to get the value. Example:

// The value will be output of Animal's String() func.
// Map will panic if Animal does not implement String().
Field *Animal `structs:"field,string"`

A tag value with the option of "flatten" used in a struct field is to flatten its fields in the output map. Example:

// The FieldStruct's fields will be flattened into the output map.
FieldStruct time.Time `structs:",flatten"`

A tag value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Field is not processed further by this package.
Field time.Time     `structs:"myName,omitnested"`
Field *http.Request `structs:",omitnested"`

A tag value with the option of "omitempty" ignores that particular field if the field value is empty. Example:

// Field appears in map as key "myName", but the field is
// skipped if empty.
Field string `structs:"myName,omitempty"`

// Field appears in map as key "Field" (the default), but
// the field is skipped if empty.
Field string `structs:",omitempty"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected.

func (*Struct) Name

func (s *Struct) Name() string

Name returns the structs's type name within its package. For more info refer to Name() function.

func (*Struct) Names

func (s *Struct) Names() []string

Names returns a slice of field names. A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

It panics if s's kind is not struct.

func (*Struct) Values

func (s *Struct) Values() []interface{}

Values converts the given s struct's field values to a []interface{}. A struct tag with the content of "-" ignores the that particular field. Example:

// Field is ignored by this package.
Field int `structs:"-"`

A value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Fields is not processed further by this package.
Field time.Time     `structs:",omitnested"`
Field *http.Request `structs:",omitnested"`

A tag value with the option of "omitempty" ignores that particular field and is not added to the values if the field value is empty. Example:

// Field is skipped if empty
Field string `structs:",omitempty"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected.

Jump to

Keyboard shortcuts

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