Compare commits

...

8 commits

Author SHA1 Message Date
piyongcai
d42519b6cd
Merge 86c2d2acf2 into d00399e161 2024-02-19 21:37:10 -07:00
Dovydas
d00399e161
Add NewFromBigRat constructor (#288) 2024-02-19 23:13:43 +01:00
13981712066
86c2d2acf2 Merge branch 'master' of https://github.com/piyongcai/decimal 2021-11-23 16:18:32 +08:00
13981712066
519f778aec add MsgPack Marshal And Unmarshal function 2021-11-23 16:16:27 +08:00
piyongcai
2371d4b37d
Merge branch 'shopspring:master' into master 2021-11-23 16:10:50 +08:00
13981712066
54fa471190 remove github.com/tinylib/msgp 2021-10-17 19:47:28 +08:00
13981712066
bc0ec03c77 rename package to piyongcai 2021-10-15 14:20:41 +08:00
13981712066
37706fc9ff For MessagePack Add github.com/tinylib/msgp 2021-10-15 14:11:52 +08:00
5 changed files with 173 additions and 1 deletions

1
.gitignore vendored
View file

@ -4,6 +4,7 @@
# IntelliJ # IntelliJ
.idea/ .idea/
*.iml *.iml
*.sum
# VS code # VS code
*.code-workspace *.code-workspace

View file

@ -124,6 +124,26 @@ func NewFromBigInt(value *big.Int, exp int32) Decimal {
} }
} }
// NewFromBigRat returns a new Decimal from a big.Rat. The numerator and
// denominator are divided and rounded to the given precision.
//
// Example:
//
// d1 := NewFromBigRat(big.NewRat(0, 1), 0) // output: "0"
// d2 := NewFromBigRat(big.NewRat(4, 5), 1) // output: "0.8"
// d3 := NewFromBigRat(big.NewRat(1000, 3), 3) // output: "333.333"
// d4 := NewFromBigRat(big.NewRat(2, 7), 4) // output: "0.2857"
//
func NewFromBigRat(value *big.Rat, precision int32) Decimal {
return Decimal{
value: new(big.Int).Set(value.Num()),
exp: 0,
}.DivRound(Decimal{
value: new(big.Int).Set(value.Denom()),
exp: 0,
}, precision)
}
// NewFromString returns a new Decimal from a string representation. // NewFromString returns a new Decimal from a string representation.
// Trailing zeroes are not trimmed. // Trailing zeroes are not trimmed.
// //

90
decimal_gen.go Normal file
View file

@ -0,0 +1,90 @@
package decimal
import (
"errors"
)
var (
errShortBytes = errors.New("msgp: too few bytes left to read object")
)
// MarshalMsg implements msgp.Marshaler
func (d Decimal) MarshalMsg(b []byte) (o []byte, err error) {
o = require(b, d.Msgsize())
str := d.String()
sz := len(str)
if sz > 30 {
sz = 30
if str[29] == '.' {
sz = 29
}
str = str[:sz]
}
o, n := ensure(b, 1+sz)
o[n] = byte(0xa0 | sz)
n++
return o[:n+copy(o[n:], str)], nil
}
// UnmarshalMsg implements msgp.Unmarshaler
func (d *Decimal) UnmarshalMsg(b []byte) (o []byte, err error) {
l := len(b)
if l < 1 {
return nil, errShortBytes
}
sz := int(b[0] & 0x1f)
if len(b[1:]) < sz {
err = errShortBytes
return
}
if *d, err = NewFromString(string(b[1 : sz+1])); err == nil {
o = b[sz:]
}
return
}
// Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message
func (d Decimal) Msgsize() int {
return 31
}
// Require ensures that cap(old)-len(old) >= extra.
func require(old []byte, extra int) []byte {
l := len(old)
c := cap(old)
r := l + extra
if c >= r {
return old
} else if l == 0 {
return make([]byte, 0, extra)
}
// the new size is the greater
// of double the old capacity
// and the sum of the old length
// and the number of new bytes
// necessary.
c <<= 1
if c < r {
c = r
}
n := make([]byte, l, c)
copy(n, old)
return n
}
// ensure 'sz' extra bytes in 'b' btw len(b) and cap(b)
func ensure(b []byte, sz int) ([]byte, int) {
l := len(b)
c := cap(b)
if c-l < sz {
o := make([]byte, (2*c)+sz) // exponential growth
n := copy(o, b)
return o[:n+sz], n
}
return b[:l+sz], l
}

View file

@ -2,6 +2,7 @@ package decimal
import ( import (
"database/sql/driver" "database/sql/driver"
"encoding/base64"
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
@ -556,6 +557,51 @@ func TestNewFromBigIntWithExponent(t *testing.T) {
} }
} }
func TestNewFromBigRat(t *testing.T) {
mustParseRat := func(val string) *big.Rat {
num, _ := new(big.Rat).SetString(val)
return num
}
type Inp struct {
val *big.Rat
prec int32
}
tests := map[Inp]string{
Inp{big.NewRat(0, 1), 16}: "0",
Inp{big.NewRat(4, 5), 16}: "0.8",
Inp{big.NewRat(10, 2), 16}: "5",
Inp{big.NewRat(1023427554493, 43432632), 16}: "23563.5628642767953828", // rounded
Inp{big.NewRat(1, 434324545566634), 16}: "0.0000000000000023",
Inp{big.NewRat(1, 3), 16}: "0.3333333333333333",
Inp{big.NewRat(2, 3), 2}: "0.67", // rounded
Inp{big.NewRat(2, 3), 16}: "0.6666666666666667", // rounded
Inp{big.NewRat(10000, 3), 16}: "3333.3333333333333333",
Inp{mustParseRat("30702832066636633479"), 16}: "30702832066636633479",
Inp{mustParseRat("487028320159896636679.1827512895753"), 16}: "487028320159896636679.1827512895753",
Inp{mustParseRat("127028320612589896636633479.173582751289575278357832"), -2}: "127028320612589896636633500", // rounded
Inp{mustParseRat("127028320612589896636633479.173582751289575278357832"), 16}: "127028320612589896636633479.1735827512895753", // rounded
Inp{mustParseRat("127028320612589896636633479.173582751289575278357832"), 32}: "127028320612589896636633479.173582751289575278357832",
}
// add negatives
for p, s := range tests {
if p.val.Cmp(new(big.Rat)) > 0 {
tests[Inp{p.val.Neg(p.val), p.prec}] = "-" + s
}
}
for input, s := range tests {
d := NewFromBigRat(input.val, input.prec)
if d.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, d.String(),
d.value.String(), d.exp)
}
}
}
func TestCopy(t *testing.T) { func TestCopy(t *testing.T) {
origin := New(1, 0) origin := New(1, 0)
cpy := origin.Copy() cpy := origin.Copy()
@ -3407,3 +3453,18 @@ func ExampleNewFromFloat() {
//0.123123123123123 //0.123123123123123
//-10000000000000 //-10000000000000
} }
func TestMsgPack(t *testing.T) {
d, _ := NewFromString("79228162514264337593543950334.123222")
out, err := d.MarshalMsg(nil)
if err != nil {
t.Fatal(err)
}
t.Log(base64.StdEncoding.EncodeToString(out))
var d2 = Decimal{}
if _, err = d2.UnmarshalMsg(out); err != nil {
t.Fatal(err)
}
t.Log(d2.String())
}

2
go.mod
View file

@ -1,3 +1,3 @@
module github.com/shopspring/decimal module github.com/piyongcai/decimal
go 1.7 go 1.7