Skip to content

Commit

Permalink
GH-38477: [Go] Fixing decimal 128 rounding issue (#38478)
Browse files Browse the repository at this point in the history
### Rationale for this change
Fixing an off-by-one rounding issue with decimal128 by ensuring proper precision handling.

### Are these changes tested?
The test case which reproduced the rounding issue has been added as a unit test.

* Closes: #38477

Authored-by: Matt Topol <zotthewizard@gmail.com>
Signed-off-by: Matt Topol <zotthewizard@gmail.com>
  • Loading branch information
zeroshade authored Nov 14, 2023
1 parent f3ec224 commit bb7ffaf
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
4 changes: 2 additions & 2 deletions go/arrow/decimal128/decimal128.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func FromString(v string, prec, scale int32) (n Num, err error) {
var precInBits = uint(math.Round(float64(prec+scale+1)/math.Log10(2))) + 1

var out *big.Float
out, _, err = big.ParseFloat(v, 10, 127, big.ToNearestEven)
out, _, err = big.ParseFloat(v, 10, 128, big.ToNearestEven)
if err != nil {
return
}
Expand All @@ -280,7 +280,7 @@ func FromString(v string, prec, scale int32) (n Num, err error) {
// (e.g. C++) handles Decimal values. So if we're negative we'll subtract 0.5 and if
// we're positive we'll add 0.5.
p := (&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())
out.Mul(out, p).SetPrec(precInBits)
out.SetPrec(precInBits).Mul(out, p)
if out.Signbit() {
out.Sub(out, pt5)
} else {
Expand Down
9 changes: 9 additions & 0 deletions go/arrow/decimal128/decimal128_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"github.com/apache/arrow/go/v15/arrow/decimal128"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestFromU64(t *testing.T) {
Expand Down Expand Up @@ -698,3 +699,11 @@ func TestBitLen(t *testing.T) {
_, err = decimal128.FromString(b.String(), decimal128.MaxPrecision, -1)
assert.ErrorContains(t, err, "bitlen too large for decimal128")
}

func TestFromStringDecimal128b(t *testing.T) {
const decStr = "9323406071781562130.6457232358109488923"

num, err := decimal128.FromString(decStr, 38, 19)
require.NoError(t, err)
assert.Equal(t, decStr, num.ToString(19))
}

0 comments on commit bb7ffaf

Please sign in to comment.