Compare commits

...

6 commits

Author SHA1 Message Date
Jim McDonald
649ecfd7ef
Merge c31da0254a into 645a76e5b0 2024-04-06 23:09:12 -02:30
Philip Dubé
645a76e5b0
Optimize BigInt (#359) 2024-04-05 21:43:23 +02:00
Mateusz Woś
ed8f76e893
Drop support for Go versions older than 1.10 (#361)
* Drop support for Go versions older than 1.10
* Remove 1.18 from test suite
2024-04-05 21:41:05 +02:00
Mateusz Woś
0e69d5cd53
Run CI on both push to origin branches and pull requests (#360) 2024-04-04 16:35:31 +02:00
Philip Dubé
bf7794e1a8
Optimize NumDigits method (#356) 2024-04-04 16:14:38 +02:00
Jim McDonald
c31da0254a
Add Format() 2022-04-11 17:45:30 +01:00
6 changed files with 175 additions and 59 deletions

View file

@ -1,11 +1,15 @@
name: ci name: ci
on: [push] on:
push:
branches:
- master
pull_request:
jobs: jobs:
ci-job: ci-job:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
go: [ '1.7.x', '1.18', '1.19', '1.20', '1.21', '1.x' ] go: [ '1.10.x', '1.19', '1.20', '1.21', '1.22', '1.x' ]
name: Go ${{ matrix.go }} name: Go ${{ matrix.go }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

View file

@ -22,7 +22,7 @@ Run `go get github.com/shopspring/decimal`
## Requirements ## Requirements
Decimal library requires Go version `>=1.7` Decimal library requires Go version `>=1.10`
## Usage ## Usage

View file

@ -1224,14 +1224,33 @@ func (d Decimal) Ln(precision int32) (Decimal, error) {
} }
// NumDigits returns the number of digits of the decimal coefficient (d.Value) // 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 (d Decimal) NumDigits() int { func (d Decimal) NumDigits() int {
d.ensureInitialized() if d.value == nil {
// Note(mwoss): It can be optimized, unnecessary cast of big.Int to string return 1
if d.IsNegative() {
return len(d.value.String()) - 1
} }
return len(d.value.String())
if d.value.IsInt64() {
i64 := d.value.Int64()
// restrict fast path to integers with exact conversion to float64
if i64 <= (1<<53) && i64 >= -(1<<53) {
if i64 == 0 {
return 1
}
return int(math.Log10(math.Abs(float64(i64)))) + 1
}
}
estimatedNumDigits := int(float64(d.value.BitLen()) / math.Log2(10))
// estimatedNumDigits (lg10) may be off by 1, need to verify
digitsBigInt := big.NewInt(int64(estimatedNumDigits))
errorCorrectionUnit := digitsBigInt.Exp(tenInt, digitsBigInt, nil)
if d.value.CmpAbs(errorCorrectionUnit) >= 0 {
return estimatedNumDigits + 1
}
return estimatedNumDigits
} }
// IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false. // IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false.
@ -1387,9 +1406,7 @@ func (d Decimal) IntPart() int64 {
// BigInt returns integer component of the decimal as a BigInt. // BigInt returns integer component of the decimal as a BigInt.
func (d Decimal) BigInt() *big.Int { func (d Decimal) BigInt() *big.Int {
scaledD := d.rescale(0) scaledD := d.rescale(0)
i := &big.Int{} return scaledD.value
i.SetString(scaledD.String(), 10)
return i
} }
// BigFloat returns decimal as BigFloat. // BigFloat returns decimal as BigFloat.
@ -1443,6 +1460,73 @@ func (d Decimal) String() string {
return d.string(true) 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 // StringFixed returns a rounded fixed-point string with places digits after
// the decimal point. // the decimal point.
// //
@ -1872,48 +1956,7 @@ func (d Decimal) StringScaled(exp int32) string {
} }
func (d Decimal) string(trimTrailingZeros bool) string { func (d Decimal) string(trimTrailingZeros bool) string {
if d.exp >= 0 { return d.Format("", ".", trimTrailingZeros)
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
} }
func (d *Decimal) ensureInitialized() { func (d *Decimal) ensureInitialized() {

View file

@ -121,6 +121,34 @@ func BenchmarkDecimal_RoundCash_Five(b *testing.B) {
} }
} }
func numDigits(b *testing.B, want int, val Decimal) {
b.Helper()
for i := 0; i < b.N; i++ {
if have := val.NumDigits(); have != want {
b.Fatalf("\nHave: %d\nWant: %d", have, want)
}
}
}
func BenchmarkDecimal_NumDigits10(b *testing.B) {
numDigits(b, 10, New(3478512345, -3))
}
func BenchmarkDecimal_NumDigits100(b *testing.B) {
s := make([]byte, 102)
for i := range s {
s[i] = byte('0' + i%10)
}
s[0] = '-'
s[100] = '.'
d, err := NewFromString(string(s))
if err != nil {
b.Log(d)
b.Error(err)
}
numDigits(b, 100, d)
}
func Benchmark_Cmp(b *testing.B) { func Benchmark_Cmp(b *testing.B) {
decimals := DecimalSlice([]Decimal{}) decimals := DecimalSlice([]Decimal{})
for i := 0; i < 1000000; i++ { for i := 0; i < 1000000; i++ {
@ -132,7 +160,7 @@ func Benchmark_Cmp(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Add_different_precision(b *testing.B) { func BenchmarkDecimal_Add_different_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500).Mul(NewFromFloat(0.12)) d2 := NewFromFloat(500).Mul(NewFromFloat(0.12))
@ -143,7 +171,7 @@ func Benchmark_decimal_Decimal_Add_different_precision(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Sub_different_precision(b *testing.B) { func BenchmarkDecimal_Sub_different_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500).Mul(NewFromFloat(0.12)) d2 := NewFromFloat(500).Mul(NewFromFloat(0.12))
@ -154,7 +182,7 @@ func Benchmark_decimal_Decimal_Sub_different_precision(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Add_same_precision(b *testing.B) { func BenchmarkDecimal_Add_same_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500.123) d2 := NewFromFloat(500.123)
@ -165,7 +193,7 @@ func Benchmark_decimal_Decimal_Add_same_precision(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Sub_same_precision(b *testing.B) { func BenchmarkDecimal_Sub_same_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500.123) d2 := NewFromFloat(500.123)

View file

@ -1513,6 +1513,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) { func TestDecimal_BankRoundAndStringFixed(t *testing.T) {
type testData struct { type testData struct {
input string input string

2
go.mod
View file

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