Skip to content

Commit

Permalink
Fix numeric to float64 conversion
Browse files Browse the repository at this point in the history
A previous optimization in 50933c0 had a logic bug when converting
pgtype.Numeric to a float64:

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

An exponent of one means multiply by 10.

#210
  • Loading branch information
jschaf authored and jackc committed Feb 6, 2024
1 parent 31dd0e4 commit f620c0f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
5 changes: 4 additions & 1 deletion numeric.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,8 +448,11 @@ func (src *Numeric) toFloat64() (float64, error) {
return math.Inf(-1), nil
}

if src.Exp == 1 {
switch {
case src.Exp == 0:
return float64(src.Int.Int64()), nil
case src.Exp == 1:
return float64(src.Int.Int64() * 10), nil
}

buf := make([]byte, 0, 32)
Expand Down
20 changes: 20 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,22 @@ func TestNumericSmallNegativeValues(t *testing.T) {
t.Fatalf("expected %s, got %s", "-0.000123", s)
}
}

// https://github.com/jackc/pgtype/issues/210
func TestNumericFloat64(t *testing.T) {
n := pgtype.Numeric{
Int: big.NewInt(5),
Exp: 1,
Status: pgtype.Present,
}

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

if f != 50.0 {
t.Fatalf("expected %s, got %f", "50", f)
}
}

0 comments on commit f620c0f

Please sign in to comment.