NewFromFloat loses precision
See this [example](https://goplay.tools/snippet/WUPyGslBHTi):
```
package main
import (
"math/rand/v2"
"testing"
"github.com/shopspring/decimal"
)
func Test(t *testing.T) {
// This number is exactly representable as a float64:
f64 := float64(rand.Int64())
t.Logf("Number: %f", f64)
fromInt := decimal.NewFromInt(int64(f64))
fromFloat := decimal.NewFromFloat(f64)
if fromInt.Cmp(fromFloat) != 0 {
t.Errorf("from-float (%v) != from-int (%v)", fromFloat, fromInt)
}
}
```
The above outputs something like:
```
=== RUN Test
prog_test.go:14: Number: 5202671607238904832.000000
prog_test.go:21: dec2 (5202671607238905000) != original (5202671607238904832)
--- FAIL: Test (0.00s)
FAIL
```
The original number is 5202671607238904832, but the NewFromFloat-created Decimal is 5202671607238905000.
关闭于 2025-10-04 1 条评论