Compare commits

...

7 commits

Author SHA1 Message Date
Jim McDonald
515d14bed8
Merge c31da0254a into a1bdfc355e 2024-04-23 13:21:01 +09:00
Mateusz Woś
a1bdfc355e
Release version 1.4.0 (#365) 2024-04-12 16:19:23 +02:00
Mateusz Woś
275e48eaef
Add docs section with alternative libraries (#363) 2024-04-12 15:40:04 +02:00
Philip Dubé
dd603cbbbd
Support scanning uint64 (#364) 2024-04-12 15:35:56 +02:00
Egor Seredin
80ec940054
Add NewFromUint64 constructor (#352) 2024-04-08 16:38:20 +02:00
Mateusz Woś
2fa107d0fe
Remove production usage from docs (#362) 2024-04-07 20:33:44 +02:00
Jim McDonald
c31da0254a
Add Format() 2022-04-11 17:45:30 +01:00
4 changed files with 222 additions and 130 deletions

View file

@ -1,3 +1,30 @@
## Decimal v1.4.0
#### BREAKING
- Drop support for Go version older than 1.10 [#361](https://github.com/shopspring/decimal/pull/361)
#### FEATURES
- Add implementation of natural logarithm [#339](https://github.com/shopspring/decimal/pull/339) [#357](https://github.com/shopspring/decimal/pull/357)
- Add improved implementation of power operation [#358](https://github.com/shopspring/decimal/pull/358)
- Add Compare method which forwards calls to Cmp [#346](https://github.com/shopspring/decimal/pull/346)
- Add NewFromBigRat constructor [#288](https://github.com/shopspring/decimal/pull/288)
- Add NewFromUint64 constructor [#352](https://github.com/shopspring/decimal/pull/352)
#### ENHANCEMENTS
- Migrate to Github Actions [#245](https://github.com/shopspring/decimal/pull/245) [#340](https://github.com/shopspring/decimal/pull/340)
- Fix examples for RoundDown, RoundFloor, RoundUp, and RoundCeil [#285](https://github.com/shopspring/decimal/pull/285) [#328](https://github.com/shopspring/decimal/pull/328) [#341](https://github.com/shopspring/decimal/pull/341)
- Use Godoc standard to mark deprecated Equals and StringScaled methods [#342](https://github.com/shopspring/decimal/pull/342)
- Removed unnecessary min function for RescalePair method [#265](https://github.com/shopspring/decimal/pull/265)
- Avoid reallocation of initial slice in MarshalBinary (GobEncode) [#355](https://github.com/shopspring/decimal/pull/355)
- Optimize NumDigits method [#301](https://github.com/shopspring/decimal/pull/301) [#356](https://github.com/shopspring/decimal/pull/356)
- Optimize BigInt method [#359](https://github.com/shopspring/decimal/pull/359)
- Support scanning uint64 [#131](https://github.com/shopspring/decimal/pull/131) [#364](https://github.com/shopspring/decimal/pull/364)
- Add docs section with alternative libraries [#363](https://github.com/shopspring/decimal/pull/363)
#### BUGFIXES
- Fix incorrect calculation of decimal modulo [#258](https://github.com/shopspring/decimal/pull/258) [#317](https://github.com/shopspring/decimal/pull/317)
- Allocate new(big.Int) in Copy method to deeply clone it [#278](https://github.com/shopspring/decimal/pull/278)
- Fix overflow edge case in QuoRem method [#322](https://github.com/shopspring/decimal/pull/322)
## Decimal v1.3.1
#### ENHANCEMENTS

View file

@ -24,6 +24,11 @@ Run `go get github.com/shopspring/decimal`
Decimal library requires Go version `>=1.10`
## Documentation
http://godoc.org/github.com/shopspring/decimal
## Usage
```go
@ -59,14 +64,16 @@ func main() {
}
```
## Documentation
## Alternative libraries
http://godoc.org/github.com/shopspring/decimal
When working with decimal numbers, you might face problems this library is not perfectly suited for.
Fortunately, thanks to the wonderful community we have a dozen other libraries that you can choose from.
Explore other alternatives to find the one that best fits your needs :)
## Production Usage
* [Spring](https://shopspring.com/), since August 14, 2014.
* If you are using this in production, please let us know!
* [cockroachdb/apd](https://github.com/cockroachdb/apd) - arbitrary precision, mutable and rich API similar to `big.Int`, more performant than this library
* [alpacahq/alpacadecimal](https://github.com/alpacahq/alpacadecimal) - high performance, low precision (12 digits), fully compatible API with this library
* [govalues/decimal](https://github.com/govalues/decimal) - high performance, zero-allocation, low precision (19 digits)
* [greatcloak/decimal](https://github.com/greatcloak/decimal) - fork focusing on billing and e-commerce web application related use cases, includes out-of-the-box BSON marshaling support
## FAQ

View file

@ -130,6 +130,18 @@ func NewFromInt32(value int32) Decimal {
}
}
// NewFromUint64 converts an uint64 to Decimal.
//
// Example:
//
// NewFromUint64(123).String() // output: "123"
func NewFromUint64(value uint64) Decimal {
return Decimal{
value: new(big.Int).SetUint64(value),
exp: 0,
}
}
// NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp
func NewFromBigInt(value *big.Int, exp int32) Decimal {
return Decimal{
@ -1460,6 +1472,73 @@ func (d Decimal) String() string {
return d.string(true)
}
// Format formats a decimal.
// thousandsSeparator can be empty, in which case the integer value will be displayed without separation.
// if decimalSeparator is empty and the value is a decimal this will panic.
func (d Decimal) Format(thousandsSeparator string, decimalSeparator string, trimTrailingZeros bool) string {
if d.exp >= 0 {
d = d.rescale(0)
}
abs := new(big.Int).Abs(d.value)
str := abs.String()
var intPart, fractionalPart string
// NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
// and you are on a 32-bit machine. Won't fix this super-edge case.
dExpInt := int(d.exp)
if len(str) > -dExpInt {
intPart = str[:len(str)+dExpInt]
fractionalPart = str[len(str)+dExpInt:]
} else {
intPart = "0"
num0s := -dExpInt - len(str)
fractionalPart = strings.Repeat("0", num0s) + str
}
if thousandsSeparator != "" {
parts := 1 + (len(intPart)-1)/3
if parts > 1 {
intParts := make([]string, 1+(len(intPart)-1)/3)
offset := len(intPart) - (len(intParts)-1)*3
for i := 0; i < len(intParts); i++ {
if i == 0 {
intParts[i] = intPart[0:offset]
} else {
intParts[i] = intPart[(i-1)*3+offset : i*3+offset]
}
}
intPart = strings.Join(intParts, thousandsSeparator)
}
}
if trimTrailingZeros {
i := len(fractionalPart) - 1
for ; i >= 0; i-- {
if fractionalPart[i] != '0' {
break
}
}
fractionalPart = fractionalPart[:i+1]
}
if fractionalPart != "" && decimalSeparator == "" {
panic("no decimal separator for non-integer")
}
number := intPart
if len(fractionalPart) > 0 {
number += decimalSeparator + fractionalPart
}
if d.value.Sign() < 0 {
return "-" + number
}
return number
}
// StringFixed returns a rounded fixed-point string with places digits after
// the decimal point.
//
@ -1835,6 +1914,11 @@ func (d *Decimal) Scan(value interface{}) error {
*d = New(v, 0)
return nil
case uint64:
// while clickhouse may send 0 in db as uint64
*d = NewFromUint64(v)
return nil
default:
// default is trying to interpret value stored as string
str, err := unquoteIfQuoted(v)
@ -1889,48 +1973,7 @@ func (d Decimal) StringScaled(exp int32) string {
}
func (d Decimal) string(trimTrailingZeros bool) string {
if d.exp >= 0 {
return d.rescale(0).value.String()
}
abs := new(big.Int).Abs(d.value)
str := abs.String()
var intPart, fractionalPart string
// NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
// and you are on a 32-bit machine. Won't fix this super-edge case.
dExpInt := int(d.exp)
if len(str) > -dExpInt {
intPart = str[:len(str)+dExpInt]
fractionalPart = str[len(str)+dExpInt:]
} else {
intPart = "0"
num0s := -dExpInt - len(str)
fractionalPart = strings.Repeat("0", num0s) + str
}
if trimTrailingZeros {
i := len(fractionalPart) - 1
for ; i >= 0; i-- {
if fractionalPart[i] != '0' {
break
}
}
fractionalPart = fractionalPart[:i+1]
}
number := intPart
if len(fractionalPart) > 0 {
number += "." + fractionalPart
}
if d.value.Sign() < 0 {
return "-" + number
}
return number
return d.Format("", ".", trimTrailingZeros)
}
func (d *Decimal) ensureInitialized() {

View file

@ -480,6 +480,7 @@ func TestNewFromInt(t *testing.T) {
1: "1",
323412345: "323412345",
9223372036854775807: "9223372036854775807",
-9223372036854775808: "-9223372036854775808",
}
// add negatives
@ -505,6 +506,7 @@ func TestNewFromInt32(t *testing.T) {
1: "1",
323412345: "323412345",
2147483647: "2147483647",
-2147483648: "-2147483648",
}
// add negatives
@ -524,6 +526,25 @@ func TestNewFromInt32(t *testing.T) {
}
}
func TestNewFromUint64(t *testing.T) {
tests := map[uint64]string{
0: "0",
1: "1",
323412345: "323412345",
9223372036854775807: "9223372036854775807",
18446744073709551615: "18446744073709551615",
}
for input, s := range tests {
d := NewFromUint64(input)
if d.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, d.String(),
d.value.String(), d.exp)
}
}
}
func TestNewFromBigIntWithExponent(t *testing.T) {
type Inp struct {
val *big.Int
@ -1513,6 +1534,47 @@ func TestDecimal_RoundDownAndStringFixed(t *testing.T) {
}
}
func TestDecimal_Format(t *testing.T) {
type testData struct {
input string
thousandsSeparator string
decimalSeparator string
trimTrailingZeros bool
expected string
}
tests := []testData{
{"0", ",", ".", false, "0"},
{"0", ",", ".", true, "0"},
{"999", ",", ".", true, "999"},
{"1000", ",", ".", true, "1,000"},
{"123", ",", ".", true, "123"},
{"1234", ",", ".", true, "1,234"},
{"12345.67", "", ".", true, "12345.67"},
{"12345.00", ",", ".", true, "12,345"},
{"12345.00", ",", ".", false, "12,345.00"},
{"123456.00", ",", ".", false, "123,456.00"},
{"1234567.00", ",", ".", false, "1,234,567.00"},
{"1234567.00", ".", ",", false, "1.234.567,00"},
{"1234567.00", "_", ".", true, "1_234_567"},
{"-12.00", "_", ".", true, "-12"},
{"-123.00", "_", ".", true, "-123"},
{"-1234.00", "_", ".", true, "-1_234"},
}
for _, test := range tests {
d, err := NewFromString(test.input)
if err != nil {
panic(err)
}
got := d.Format(test.thousandsSeparator, test.decimalSeparator, test.trimTrailingZeros)
if got != test.expected {
t.Errorf("Format %s got %s, expected %s",
d, got, test.expected)
}
}
}
func TestDecimal_BankRoundAndStringFixed(t *testing.T) {
type testData struct {
input string
@ -2395,104 +2457,57 @@ func TestDecimal_Max(t *testing.T) {
}
}
func TestDecimal_Scan(t *testing.T) {
// test the Scan method that implements the
// sql.Scanner interface
// check for the for different type of values
// that are possible to be received from the database
// drivers
func scanHelper(t *testing.T, dbval interface{}, expected Decimal) {
t.Helper()
// in normal operations the db driver (sqlite at least)
// will return an int64 if you specified a numeric format
a := Decimal{}
dbvalue := 54.33
expected := NewFromFloat(dbvalue)
err := a.Scan(dbvalue)
if err != nil {
if err := a.Scan(dbval); err != nil {
// Scan failed... no need to test result value
t.Errorf("a.Scan(54.33) failed with message: %s", err)
} else {
t.Errorf("a.Scan(%v) failed with message: %s", dbval, err)
} else if !a.Equal(expected) {
// Scan succeeded... test resulting values
if !a.Equal(expected) {
t.Errorf("%s does not equal to %s", a, expected)
}
}
}
func TestDecimal_Scan(t *testing.T) {
// test the Scan method that implements the sql.Scanner interface
// check different types received from various database drivers
dbvalue := 54.33
expected := NewFromFloat(dbvalue)
scanHelper(t, dbvalue, expected)
// apparently MySQL 5.7.16 and returns these as float32 so we need
// to handle these as well
dbvalueFloat32 := float32(54.33)
expected = NewFromFloat(float64(dbvalueFloat32))
err = a.Scan(dbvalueFloat32)
if err != nil {
// Scan failed... no need to test result value
t.Errorf("a.Scan(54.33) failed with message: %s", err)
} else {
// Scan succeeded... test resulting values
if !a.Equal(expected) {
t.Errorf("%s does not equal to %s", a, expected)
}
}
scanHelper(t, dbvalueFloat32, expected)
// at least SQLite returns an int64 when 0 is stored in the db
// and you specified a numeric format on the schema
dbvalueInt := int64(0)
expected = New(dbvalueInt, 0)
scanHelper(t, dbvalueInt, expected)
err = a.Scan(dbvalueInt)
if err != nil {
// Scan failed... no need to test result value
t.Errorf("a.Scan(0) failed with message: %s", err)
} else {
// Scan succeeded... test resulting values
if !a.Equal(expected) {
t.Errorf("%s does not equal to %s", a, expected)
}
}
// also test uint64
dbvalueUint64 := uint64(2)
expected = New(2, 0)
scanHelper(t, dbvalueUint64, expected)
// in case you specified a varchar in your SQL schema,
// the database driver will return byte slice []byte
// the database driver may return either []byte or string
valueStr := "535.666"
dbvalueStr := []byte(valueStr)
expected, err = NewFromString(valueStr)
expected, err := NewFromString(valueStr)
if err != nil {
t.Fatal(err)
}
err = a.Scan(dbvalueStr)
if err != nil {
// Scan failed... no need to test result value
t.Errorf("a.Scan('535.666') failed with message: %s", err)
} else {
// Scan succeeded... test resulting values
if !a.Equal(expected) {
t.Errorf("%s does not equal to %s", a, expected)
}
}
// lib/pq can also return strings
expected, err = NewFromString(valueStr)
if err != nil {
t.Fatal(err)
}
err = a.Scan(valueStr)
if err != nil {
// Scan failed... no need to test result value
t.Errorf("a.Scan('535.666') failed with message: %s", err)
} else {
// Scan succeeded... test resulting values
if !a.Equal(expected) {
t.Errorf("%s does not equal to %s", a, expected)
}
}
scanHelper(t, dbvalueStr, expected)
scanHelper(t, valueStr, expected)
type foo struct{}
a := Decimal{}
err = a.Scan(foo{})
if err == nil {
t.Errorf("a.Scan(Foo{}) should have thrown an error but did not")