Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix numeric to float64 conversion #212

Merged
merged 3 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion numeric.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ func (src *Numeric) toFloat64() (float64, error) {
return math.Inf(-1), nil
}

if src.Exp == 1 {
if src.Exp == 0 {
return float64(src.Int.Int64()), nil
}

Expand Down
26 changes: 26 additions & 0 deletions numeric_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ func TestNumericEncodeDecodeBinary(t *testing.T) {
123,
0.000012345,
1.00002345,
50.000000,
math.NaN(),
float32(math.NaN()),
math.Inf(1),
Expand Down Expand Up @@ -442,3 +443,28 @@ func TestNumericSmallNegativeValues(t *testing.T) {
t.Fatalf("expected %s, got %s", "-0.000123", s)
}
}

// https://github.com/jackc/pgtype/issues/210
func TestNumericFloat64Exhaustive(t *testing.T) {
for exp := -10; exp <= 10; exp++ {
for i := -100; i < 100; i++ {
n := pgtype.Numeric{
Int: big.NewInt(int64(i)),
Exp: int32(exp),
Status: pgtype.Present,
}

var got float64
err := n.AssignTo(&got)
if err != nil {
t.Fatal(err)
}

want := float64(i) * math.Pow10(exp)
delta := math.Abs(want * 0.0000000001)
if math.Abs(got-want) > delta {
t.Fatalf("expected %f from %de%d, got %f", want, i, exp, got)
}
}
}
}